Dynamically generated object key not updating

Viewed 287

I am using v-chip component of Vueitfy, to hide/show chip on cross icon click.The documentation states to add a boolean v-if

data() {
    return {
        chips:{},
        tests: [],
        tabs: ["Parameters", "Start Time", "Trafic Source"],
        disabledButtons: true,
    };
},

the chips object over here is what I need to make dynamic. For that I pushed the dynamically generated name in chips object:

mounted() {
    this.tests = this.$store.state.run.runScheduled;
    
    //adding dynamic chip into chips array which will be used to hide/show individual chips
    for (let test in this.tests) {
        let chipName="Chip"+test;
        this.chips[chipName]=true;
    }
}

doing the same thing for HTML markup

<div class="chips-wrapper">
  <span  v-for="(test, index) in tests"  :key="index">
    <v-chip
      v-if="`chips.Chip${test.id}`"
      class="tags"
      close
      label
      @click:close="RemoveTest(test.id)"
  >
    {{ test.name }}
  </v-chip>
  </span>
</div>

removetest() is where i need to set the check to false so that it is hidden from DOM, but for some reason the code is not working

methods: {
    RemoveTest(testID) {
      let chipName=`Chip${testID}`;
      console.log(chipName);
      this.chips.chipName=false
    },
}

if I try to print out the chips object, it shows the expected generated key/value pairs

{
  "Chip0": true,
  "Chip1": true,
  "Chip2": true,
  "Chip3": true
}

the code inside the removeTest() method should change the value to false but it's not, any help?

1 Answers

Use Vue.set (or this.$set in a component) to add properties to a data object at runtime:

for (let test in this.tests) {
   let chipName = "Chip" + test;
   this.$set(this.chips, chipName, true);
}

From Vue's reactivity docs:

Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive... However, it’s possible to add reactive properties to a nested object using the Vue.set(object, propertyName, value) method

Related