【vue】vue 全选与取消全选

知识点:

1 v-model:监听input内容

2 watch:监听属性方法
在这里插入图片描述

3 页面初始化调用函数 mounted

一:html元素

<table id="userTable" class="table table-bordered table-hover">
  <thead>
     <tr>
         <th><input type="checkbox" name='check' v-model="checkedAll" @change="changeState"></th>
         <th>编号</th>
         <th>反馈用户</th>
         <th>手机号</th>
         <th>反馈时间</th>
         <th>操作</th>
     </tr>
     </thead>
     <tbody>
	     <template v-for="item in tableList">
	         <tr>
	             <td><input type="checkbox" name='check' v-model="checkModel" :value="item.id"></td>
	             <td>{{ item.nu }}</td>
	             <td>{{ item.user.nickname }}</td>
	             <td>{{ item.user.phone}}</td>
	             <td>{{ item.times}}</td>
	             <td>
	                 <button class="btn btn-default btn-xs" v-link="{ name: 'FeedbackDetail', query: { id: item.id} }"> 查看</button>
	                 <button class="btn btn-danger btn-xs" @click="deleteQuestion(item.id)">删除</button>
	             </td>
	         </tr>
	     </template>
     </tbody>
     <tfoot>
	     <tr>
	         <td colspan="12">
	             <button class="btn btn-danger btn-xs" @click="batchRemoval()">批量移除</button>
	         </td>
	     </tr>
     </tfoot>
 </table>

如图:
在这里插入图片描述

实现思路

1 v-model 一个收集所有input(除全选框外)数组checkModel ,vue会动态将其checked为true的input的value值存入数组checkModel里

2 watch函数来监听checkModel 属性,当其长度==input元素时 全选按钮选中 否则取消

3 全选按钮v-model checkAll 属性来显示当前选中状态 click事件里 当checkAll为true时 全选 所有input按钮被选中也就是checkModel的遍历存入其value值

完整代码:

export default {
        name: "Feedback",
        data(){
            return {
                tableList: [], //所有数据
                checkModel: [], //批量选择id
                checkedAll: false, //是否是全选
            }
        },
        methods: {
            //全选
            changeState(){
                this.checkModel = [];
                if(this.checkedAll){
                    for(var i in this.tableList){
                        this.checkModel.push(this.tableList[i].id)
                    }
                }
                console.log(this.checkModel)
            }
        },
        watch:{
            checkModel :{
                handler (){
                    if(this.checkModel.length == this.tableList.length){
                        this.checkedAll = true
                    }else{
                        this.checkedAll = false
                    }
                },
                deep: true
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/LuviaWu/article/details/85262022
今日推荐