11Vue.js实现全选与反选

vue实现全选与反选

示例效果:


全选.png

反选.png

实现代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue全选与反选</title>
    <script src="./js/vue.js"></script>
</head>
<body>
    <div id="my">
        <input type="checkbox" v-model="checkAll.check" @change="checkAllChange()">
        <label>{{checkAll.name}} {{checkAll.check}}</label>
        <ul>
            <li v-for="list in lists">
                <input type="checkbox" v-model="list.check"  @change="curChange()">
                <label>{{list.name}} {{list.check}}</label>
            </li>
        </ul>
   </div>
    <script type="text/javascript">
        window.onload = function () {
            var app = new Vue({
                el: "#my",
                data: {
                    checkAll: { name: '全选', check: false },
                    lists: [{ name: '小米', check: true },
                    { name: '华为1', check: false },
                    { name: '华为2', check: false },
                    { name: '华为3', check: false },
                    { name: '华为4', check: false }]
                },
                //在methods这里面写方法、事件之类的
                methods: {
                    checkAllChange: function () {
                        //使用箭头函数 this的作用域指当前实例化对象
                        this.lists.forEach(item => {
                          
                            item.check = this.checkAll.check;
                        });
                    },
                    curChange:function(){

                        //过滤check为true的
                        var curTrue=this.lists.filter(function(item){

                            return item.check==true;
                        });

                        //判断选中的状态与总长度比较  当选中的项与总长度相等时 自动 勾选 “全选”
                        // 不相等时 取消 全选 
                        if(curTrue.length==this.lists.length){
                            this.checkAll.check=true;
                        }else{
                            this.checkAll.check=false;
                        }
                    }
                }
            })
        }
    </script>
</body>
</html>