简体   繁体   中英

How can I access data property as variable in Vue.js?

I made a function that uncheck all elements when the button is pressed. Whether it is selected or not is judged by the value of "isActive" property of each data.

  data : {
    genres : [
      { "id" : "1", "name" : "Apple",  "isActive" : true },
      { "id" : "2", "name" : "Banana", "isActive" : true },
      { "id" : "3", "name" : "Peach",  "isActive" : true }
    ],
    departments : [
      { "id" : "1", "name" : "Apple",  "isActive" : true },
      { "id" : "2", "name" : "Banana", "isActive" : true },
      { "id" : "3", "name" : "Peach",  "isActive" : true }
    ]
  }

The code for uncheck all is like this.

  methods : {
    clearAllActiveClasses(){
      this.genres.forEach(function(item){
        item.isActive = false;
      });

      this.departments.forEach(function(item){
        item.isActive = false;
      });
    }
  }

As you can see, the logic is completely same. The logic will not change in the future. Maybe.

So, in order to make these processes common, I wrote the following description.

  methods : {
    clearAllActiveClasses(){
      let itemGroups = ['genres', 'departments'];

      for(let itemGroup in itemGroups){
        let items = this[itemGroup];

        items.forEach(function(item){
          item.isActive = false;
        });
      }
    }
  }

But this code did not work.

How can I make the process common?

The issue is for...in statement iterates over all enumerable properties of an object . You need to use the for...of statement here instead, as it creates a loop iterating over iterable objects like genres & departments array in this case:

for (let itemGroup of itemGroups) {
  let items = this[itemGroup];
  items.forEach(function(item) {
    item.isActive = false;
  });
}

Fiddle Demo

You can also keep the active state in a common object using a prefix + id as key

 var app = new Vue({ el: '#app', data: { actives:{}, genres: [{id:"1",name:"Apple"},{id:"2",name:"Banana"},{id:"3",name:"Peach"}], departments:[{id:"1",name:"Apple"},{id:"2",name:"Banana"},{id:"3",name:"Peach"}] }, mounted() {}, methods: { clear() { this.actives = {}; } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @click="clear">CLEAR</button> <ul> <li> Genres <input type="checkbox" v-for="gen in genres":key="`gen-${gen.id}`" v-model="actives[`gen-${gen.id}`]" /> </li> <li> Departments <input type="checkbox" v-for="dep in departments":key="`dep-${dep.id}`" v-model="actives[`dep-${dep.id}`]" /> </li> </ul> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM