Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

在vue组件中,自定义变量是否会导致内存泄漏?

  • 父组件
<template>
  <child v-if="show"/>
   <button @click="show = !show">test</button>
</template>

<script>
export default {
  data() {
    return {
      show: false,
    }
  }
}
</script>
  • 子组件
<template>
  <div>child组件</div>
  <div>{{list.join(',')}}</div> 
  <button @click="add">增加数组项</button>
</template>

const _data = {
  list: []
}
export default {
  data() {
    return {
      list: [],
    }
  },
  mounted() {
    this.list = _data.list
  },
  methods: {
    add() {
      _data.list.push(111)
    }
  } 
}
</script>

我在子组件定义一个变量_data,并增加数据项111,然后点击test按钮v-if销毁组件,再点击test显示child组件,结果看到_data数据还是添加了111。我猜是内存泄漏的问题,想了解下原理,同时想问下如果在vue组件中使用了类似这种_data的自定义变量如何防止内存泄漏,谢谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

相当于调用该组件的都可以用到的全局变量。如果你不需要,就包在data里面。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...