vue的依赖属性改变为什么计算属性未变?

问题描述

计算属性newMessage依赖this.serieFormType和this.currIndex属性,当把this.serieFormType改为“add”后,再修改this.currIndex,newMessage这个函数不再执行了,根据computed缓存原理,newMessage只依赖
this.serieFormType的话,那么不执行是又道理的,可是newMessage不是同样依赖了this.currIndex吗?为什么
this.currIndex改变,未触发computed函数执行?

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

 data () {
    return {
      currIndex: 0,
      serieFormType: 'change',
      arr: ['aaa', 'bbb', 'ccc'],
    }
  },

computed: {
    newMessage() {
      console.log('run');
      if (this.serieFormType === 'add') {
        return {};
      }
      if (this.arr.length) {
        return this.arr[this.currIndex];
      }
      return {};
    }
  },
阅读 4.6k
4 个回答

因为计算属性每次取值都会触发一次依赖收集,newMessage的computed watcher在serieFormType === 'add'的条件下,取值函数执行到第一个return 就结束了,所以只会对serieFormType这个数据的产生依赖,并且由于watcher的cleanupDeps机制,会取消之前对其他数据产生的依赖。

newMessage页面中使用过没有

this.seriesFormType被改为add之后,后面的就被阻断了,执行不到

推荐问题