【问题标题】:How do I display a second array inside my computed property in vue.js如何在 vue.js 的计算属性中显示第二个数组
【发布时间】:2019-10-28 20:40:05
【问题描述】:

我想在我的计算属性中显示第二个数组,但前提是选中了一个复选框。否则应该只显示第一个列表。

我已经设法让我的第一个列表与我的代码一起工作并且它应该显示,我还有一个方法可以使列表按字母顺序排序(这就是我所说的类别)。

如果我的复选框值为真,我如何合并到另一个数组中?

这里有一些代码

data: function() {
   return {
     checked: false,
     fruitList: [ //Fist list
       "Apple",
       "Grapes",
       "Mango",
       "Oranges",
       "Banana",
       "Dragon fruit",
       "Pinapple",
       "Coconut",
       "Strawberry"
     ],
      vegetableList:[ //Second list, should only display if checkbox is true
      "cucumber",
       "tomato",
       "onion"
       ]
    };
},
methods:{
return{
 sorted(list) {
     return list.sort();
   }
}
},
computed: {
   categorizedWords() {
     let map = {};
      this.fruitList.forEach(word => {
       let key = word.charAt(0).toUpperCase();
       let list = map[key];
       if (list === undefined) {
         list = [];
         map[key] = this.sortedList(list);
       }
       list.push(word);
     });

     var sortedCategories = this.sortedList(Object.keys(map));
     var sortedMap = sortedCategories.map(category => {
       return { category: category, word: map[category] };
     });
     return sortedMap;
   }
 }


【问题讨论】:

    标签: vue.js computed-properties


    【解决方案1】:

    好的,所以我已经完全掌握了,现在我已经弄清楚了。 所以我把我的代码改成了这个,它起作用了,这是在我的计算属性中:

     computed: {
       categorizedWords() {
         let map = {};
         let isCheched = this.checked;
    
          let allGreens = this.fruitList;
    
          if (isChecked === true) {
            allGreens = allGreens.concat(this.vegetableList);
          }
    
          allGreens.forEach(word => {
           let key = word.charAt(0).toUpperCase();
           let list = map[key];
           if (list === undefined) {
             list = [];
             map[key] = this.sortedList(list);
           }
           list.push(word);
         });
    
         var sortedCategories = this.sortedList(Object.keys(map));
         var sortedMap = sortedCategories.map(category => {
           return { category: category, word: map[category] };
         });
         return sortedMap;
       }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-11
      • 2019-04-23
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2017-08-09
      • 2017-06-01
      • 2015-11-13
      相关资源
      最近更新 更多