美文网首页
2022-08-23 vue2.0中Computed属性触发时机

2022-08-23 vue2.0中Computed属性触发时机

作者: 小蘑菇的驼羊 | 来源:发表于2022-08-23 23:01 被阅读0次

在实际项目开发中,computed计算属性使用场景及其丰富。下面是个人的一些使用心得

1.当一个对象为计算属性时,不需要在data中定义。

2.当一个对象为计算属性时。在其方法中,使用的变量发生改变了,就会触发这个计算函数

<template>
<div>
  <el-button @click="testFunc">点我</el-button>
  <div>{{testCom}}</div>
</div>
</template>

<script>
export default {
  name: 'testComputed',
  computed: {
    testCom () {
//  可以尝试写下代码看下computed执行了几次?执行1测。因为首次加载引用了testCom。但是计算属性中,引用的testFunc方法中的age是基本数据类型。值是相等的。可以视为没改变。因此testCom不会再次触发。
      console.log('computed', this.testFunc())
      return this.testFunc()
    }
  },
  data () {
    return {
      age: 1
    }
  },
  methods: {
    testFunc () {
      this.age = 10
      return this.age
    }
  }
}
</script>

<style scoped>

</style>

在看下面代码

<template>
<div>
  <el-button @click="testFunc">点我</el-button>
  <div>{{testCom}}</div>
</div>
</template>

<script>
export default {
  name: 'testComputed',
  computed: {
    testCom () {
      console.log('computed', this.testFunc())
      return this.testFunc()
    }
  },
  data () {
    return {
      age: []//只是此处改变了
    }
  },
  methods: {
    testFunc () {
      this.age = [10]//只是此处改变了
      return this.age
    }
  }
}
</script>

<style scoped>

</style>

这样,点击按钮,就是一直触发computed属性。因为computed中testCom所依赖的testFunc方法中,age改变了。。虽然都是数组,但是引用数据类型。每次赋值都会视为新对象。可以自行使用

console.log('比较',[10]===[10])

进行输出查看。

总结来说:

当一个计算属性中,依赖于在data中定义的对象。当这个对象发生改变时,computed便会触发。当然,只是用data中定义的对象做了个console也同样适用。(个人理解,欢迎讨论)

相关文章

网友评论

      本文标题:2022-08-23 vue2.0中Computed属性触发时机

      本文链接:https://www.haomeiwen.com/subject/rghkmrtx.html