Search code examples
vue.jscomputed-properties

Computed property doesn't kick in, Vue js


I am usong Vue.js and I have created a computed property that is stored inside of my vuex. For some reason when i create my watcher and add item to the array the watcher doesn't kick in. Although, when I console log it definitely has item inside

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>

Solution

  • It looks like you're just having problems with the reactivity caveats.

    For objects: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

    For arrays: https://v2.vuejs.org/v2/guide/list.html#Caveats

    Assuming this.selectedZonesTest is an array you can't set a value by index like this:

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

    Instead you need to do something like this:

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

    Or you can use the splice method:

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

    These are limitations of the way Vue 2 detects changes. Vue 3 will use a different technique for change detection that will remove these caveats.