簡體   English   中英

如何在 Vue.js 中將數據屬性作為變量訪問?

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

我做了一個 function 在按下按鈕時取消選中所有元素。 是否被選中由每個數據的“isActive”屬性的值來判斷。

  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 }
    ]
  }

uncheck all 的代碼是這樣的。

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

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

如您所見,邏輯完全相同。 未來的邏輯不會改變。 也許。

所以,為了讓這些過程通用,我寫了下面的描述。

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

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

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

但是這段代碼不起作用。

我怎樣才能使這個過程變得通用?

問題在於for...in語句遍歷object的所有可枚舉屬性。 您需要在此處使用for...of語句,因為在這種情況下,它會創建一個遍歷可迭代對象(如genresdepartments array )的循環:

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

小提琴演示

您還可以使用前綴 + id 作為鍵將活動的 state 保留在公共 object 中

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM