vue computed 计算属性当依赖属性更新时计算属性没有执行?

computed: {    
    comp: function () {        
        return () => import(`./component/item${this.formItem.item_type}.form`);
    }
},

当我切换this.formItem.item_type的值,comp没有被触发

computed: {    
comp: function () {        
    console.log(this.formItem.item_type)        
    return () => import(`./component/item${this.formItem.item_type}.form`);
    }
},

当我加上console.log(this.formItem.item_type)时,正常触发,注释掉又不能正常触发,这是为什么呢?

另外:我使用watch去监听 正常了

watch:{    
    'formItem.item_type': function (val, oldVal) {        
    this.comp = () => import(`./component/item${this.formItem.item_type}.form`);
    }
},

补充this.formItem对象

https://img3.mukewang.com/5b47536b0001034c06970234.jpg


饮歌长啸
浏览 3725回答 2
2回答

繁华开满天机

因为只有你在计算属性内访问了相应的变量, 计算属性才能形成对其的依赖.a = () => import(`./component/item${this.formItem.item_type}.form`);当 a 函数没有调用时, this.formItem.item_type 是不会被求值的, 也就一直没有被访问过, 所以无法被计算属性收集为依赖, 你 console.log(this.formItem.item_type) 触发了 this.formItem.item_type 的访问, 完成了依赖收集, 自然没有问题.还有, 像这种永远不会被执行的代码, 也无法被收集依赖.if (false) {  a = this.formItem.item_type }解决方案:comp: function () {    // 显示的取值, 使 comp 收集依赖     this.formItem.item_type;       return () => import(`./component/item${this.formItem.item_type}.form`); }

缥缈止盈

先看一下 this.formItem.item_type 是不是响应式吧。用开发者工具展开到这一步,如果是 (...) 或者下面有浅色的 get/set 就是,不然的话,这个变量并未被观察,所以没有响应式。
打开App,查看更多内容
随时随地看视频慕课网APP