Vue 实现复选框全选,反选,单选,多选(简易版)
实现效果,如图:
HTML代码:
<template><div><div style="background-color: #f4f4f4;margin:50px 0 0 260px;width:900px;height:500px;padding:50px"><ul style="list-style: none"><li><el-checkbox v-model="allChecked" @change="handleAllChecked">全选</el-checkbox></li><li v-for="(item,index) in testList" :key="index"><el-checkbox v-model="item.isChecked" @change="handleChecked(item,$event)">{{ item.id }}</el-checkbox></li></ul></div></div></template>
JavaScript代码:
<script>export default {data () {return {allChecked: false,testList: [{id: 1 },{id: 2 },{id: 3 },{id: 4 },{id: 5 }]}},watch: {testList: {// 监听事件,监听复选框是否全部选中,全部选中则全选的复选框勾选上handler(val) {var i = 0this.testList.forEach(item => {if (item.isChecked === true) {i++}if (i === this.testList.length) {this.allChecked = true} else {this.allChecked = false}})},deep: true}},created() {this.testList.forEach(item => {// 处理后端传过来的数据,如果没有可以判断是否勾选复选框的字段,则需给数据作处理,加上一个isChecked字段,判断复选框勾选this.$set(item, 'isChecked', false) // 添加判断的字段})},methods: {handleAllChecked(v) {// 实现全选,反选(点击会传递true或者false过来)this.testList.map(item => {item.isChecked = v})},handleChecked(item, e) {// 单个选中item.isChecked = e}}}</script>