本文环境:windows7、vue2.9.6,该方法适用于所有品牌的电脑。

vue.js调用全选功能的方法:

1、从服务器拿到数据,为每个item设置checked属性

2、计算选中的数量selectCount,如果选中的数量与selectItems的数量相等,则全选selectAll选中

3、点全选时,将每个item的checked属性置为true,反选时置为false,

4、每次selectItems的属性发生变化时,都将checked的为true的item放入数组checkedGroups

下面为实现代码:

//全选
data: function() {
 return {
  selectItems: [], // 从服务器拿到的数据
 }
},
computed: {
 // 全选checkbox绑定的model
 selectAll: {
  get: function() {
   return this.selectCount == this.selectItems.length;
  },
  set: function(value) {
   this.selectItems.forEach(function(item) {
    item.checked = value;
   });
   return value;
  }
 },
 //选中的数量
 selectCount: {
  get: function() {
   var i = 0;
   this.selectItems.forEach(function(item) {
    if (item.checked) {
     i++;
    }
   });
   return i;
  }
 },
 //选中的数组
 checkedGroups: {
  get: function() {
   var checkedGroups = [];
   this.selectItems.forEach(function(item) {
    if (item.checked) {
     checkedGroups.push(item);
    }
   });
   return checkedGroups;
  }
 }
}

这种方法用起来不太方便,首先是很难复用,每次要用到的时候都需要写一次computed,其次是selectAll、checkedGroups、selectItems都已经固定,不太灵活。

所以在这次项目中,我用vue的指令重新实现了全选的功能,directive的思路其实跟computed差不多,先上代码:

export default {
 'check-all': {
  twoWay: true,
  params: ['checkData'],
  bind() {
   /**
    - 如果所有的列表的checked属性都为true,则选中全选框,否则不选中全选框
    */
   this.vm.$watch(this.params.checkData, (checkData) => {
    if (checkData.every((item) => item.checked)) {
     this.set(true);
    } else {
     this.set(false);
    }
   }, { deep: true });
  },
  // checkAll发生更改时
  update(checkAll) {
   /**
    - 如果全选框被选中,则将列表的所有checked属性转为true,否则转为false
    */
   if (checkAll) {
    this.vm[this.params.checkData].forEach((item) => {
     item.checked = true;
    });
   } else {
    this.vm[this.params.checkData].forEach((item) => {
     item.checked = false;
    });
   }
  },
 },
};

调用:

<input type="checkbox" v-model="checkAll" v-check-all="checkAll" check-data="checkData">
  <ul>
   <li v-for="item in checkData">
    <input type="checkbox" v-model="item.checked">
    {{item.text}}
   </li>
  </ul>

以上就是vue.js怎么调用全选功能的详细内容,更多请关注其它相关文章!