【问题标题】:Computed property doesn't kick in, Vue js计算属性不启动,Vue js
【发布时间】:2020-04-03 06:09:32
【问题描述】:

我使用的是 Vue.js,并且我创建了一个计算属性,该属性存储在我的 vuex 中。出于某种原因,当我创建我的观察者并将项目添加到数组中时,观察者不会启动。虽然,当我控制台日志时,它肯定里面有项目

computed:{

            selectedZonesTest(){
              return this.$store.state.selectedZonesTest;
            }
        },
       .......
            selectZones: function(ev){
                if (ev.target.className.baseVal !== null && typeof ev.target.className.baseVal !== "undefined"){
                    this.zoneId = ev.target.id
                    this.selectedZones.push({boneId:this.boneId, zoneId: this.zoneId});

                    if(this.selectedZonesTest.length == 0){
                        this.selectedZonesTest[this.boneId] = [this.zoneId];
                    }else{
                        for(var i in this.selectedZonesTest){
                            if(this.getKeyExist(this.boneId) == true){
                                if(this.zoneExists(this.zoneId) === true){
                                    // console.log("1");
                                    this.removeZone(this.zoneId)
                                }else{
                                    // console.log("2");
                                    this.selectedZonesTest[this.boneId].push(this.zoneId);
                                }
                            }else{
                                // console.log("3");
                                this.selectedZonesTest[this.boneId] = [this.zoneId];
                            }
                        }
                    }
                }
                console.log(this.selectedZonesTest);
            },
        }
    }
</script>

<style>
 .cls-1{
     fill: #fff;
 }
 .selected{
     fill: red;
 }
</style>

【问题讨论】:

  • 我怀疑以this.selectedZonesTest[this.boneId] = 开头的行。他们似乎可能违反了反应性警告。 this.selectedZonesTest 是数组还是对象?
  • 你的循环变量i没有在循环内部使用也很奇怪。
  • 我创建了循环但还没有使用它,对于 Vue.js 来说还是很新的。基本上我想要的是当一个新项目被添加到一个项目的数组中时,我试图在 UI 上显示它。我会进一步调查

标签: vue.js computed-properties


【解决方案1】:

看起来您只是在反应性警告方面遇到了问题。

对于对象:https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

对于数组:https://vuejs.org/v2/guide/list.html#Caveats

假设this.selectedZonesTest 是一个数组,您不能像这样按索引设置值:

this.selectedZonesTest[this.boneId] = [this.zoneId];

相反,您需要执行以下操作:

Vue.set(this.selectedZonesTest, this.boneId, [this.zoneId]);

或者你可以使用splice方法:

this.selectedZonesTest.splice(this.boneId, 1, [this.zoneId]);

这些是 Vue 2 检测更改方式的限制。 Vue 3 将使用一种不同的技术进行变更检测,从而消除这些警告。

【讨论】:

  • 谢谢!我刚刚阅读了警告,这是有道理的。如果你想添加到现有数组中,我会做这样的事情 this.$set(this.selectedZonesTest[this.boneId], this.zoneId) 吗?
  • @bisamov 目前您正在使用push 添加到现有数组,这应该可以正常工作。任何标准数组方法都应该可以工作。通过索引设置值时只需要使用$set。例如this.$set(this.selectedZonesTest[this.bonesId], index, this.zoneId)。即使这样,您也可以改用splice,尽管使用$set 可能会更清晰一些。
猜你喜欢
  • 2017-06-30
  • 2019-09-22
  • 2019-10-25
  • 1970-01-01
  • 2016-04-18
  • 2018-02-12
  • 2018-01-14
  • 2020-12-01
  • 2020-02-03
相关资源
最近更新 更多