Vue.js实现checkbox的全选和反选

小颖之前写的代码存在一个bug,就是当你选择全选的时候去掉后面的一个选项,再点全选结果就是反的了.很感谢博客园的朋友帮我改了这个问题嘻嘻,下面一起来看看具体是怎么实现的吧.

1.html

<template>
    <div>
<input type='checkbox' class='input-checkbox' v-model='checked' v-on:click='checkedAll'>全选 <template v-for='checkb in checkboxData'> <input type='checkbox' name='checkboxinput' class='input-checkbox' v-model='checkboxModel' value='{{checkb.id}}'>{{checkb.value}} </template>
</div> </template>

2.js

<script>
export default {
methods:{
  checkedAll: function() {
    var _this = this;
    console.log(_this.checkboxModel);
    if (this.checked) {//实现反选
      _this.checkboxModel = [];
    }else{//实现全选
      _this.checkboxModel = [];
      _this.checkboxData.forEach(function(item) {
        _this.checkboxModel.push(item.id);
      });
    }
  }
},
watch: {//深度 watcher
  'checkboxModel': {
    handler: function (val, oldVal) {
      if (this.checkboxModel.length === this.checkboxData.length) {
        this.checked=true;
      }else{
        this.checked=false;
      }
    },
    deep: true
  }
},
data () {
  return {
    checkboxData:[{
      id:'1',
      value:'苹果'
    },{
      id:'2',
      value:'荔枝'
    },{
      id:'3',
      value:'香蕉'
    },{
      id:'4',
      value:'火龙果'
    }],
    checkboxModel:['1','3','4'],
    checked:false
  }
}
}
</script>

3.watch

  • 类型:Object

  • 详细:

    一个对象,键是观察表达式,值是对应回调。值也可以是方法名,或者是对象,包含选项。在实例化时为每个键调用 $watch()

示例:

var vm = new Vue({
  data: {
    a: 1
  },
  watch: {
    'a': function (val, oldVal) {
      console.log('new: %s, old: %s', val, oldVal)
    },
    // 方法名
    'b': 'someMethod',
    // 深度 watcher
    'c': {
      handler: function (val, oldVal) { /* ... */ },
      deep: true
    }
  }
})
vm.a = 2 // -> new: 2, old: 1
posted @ 2016-06-21 10:29  爱喝酸奶的吃货  阅读(49075)  评论(18编辑  收藏  举报