直接上代码
<!DOCTYPE html>
<html lang="zh-cn">
<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 type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<style type="text/css">
#app ul {
list-style: none;
padding-left: 0px;
margin: 5px 0;
}
#app ul>li {
padding-bottom: 5px
}
</style>
<body>
<h1>vue全选反选</h1>
<hr>
<div id="app">
<label><input type="checkbox" v-model="isChecked" /> 全选/全不选</label>
<ul>
<li v-for="item in items">
<input type="checkbox" :value="item" v-model="checkedItems" />{{item}}
</li>
</ul>
<input type="button" @click="RevBtn" value="反 选" />
<input type="button" @click="sendBtn" value="提 交" />
<p v-show="checkedItems.length !== 0">{{ checkedItems }}</p>
</div>
<script type="text/javascript">
const ballGames = ['足球', '篮球', '网球', '排球', '羽毛球', '兵乓球']
// es6语法求两数组补集
function diffArr(a, b) {
return [...a.filter(x => !b.includes(x)), ...b.filter(x => !a.includes(x))]
}
var app = new Vue({
el: '#app',
data: {
items: ballGames,
checkedItems: [],
},
computed: {
isChecked: {
//判断每一个选项是否选中,如果全选中则让 全选/全不选 按钮选中
get: function() {
return this.items.length === this.checkedItems.length
},
//根据 全选/全不选 按钮的选中状态更改选项,选中则选项全部改为选中状态,不选中则反之
set: function(value) {
this.checkedItems = value ? ballGames : []
}
}
},
methods: {
RevBtn() {
this.checkedItems = diffArr(ballGames, this.checkedItems)
},
sendBtn() {
alert(this.checkedItems);
}
}
})
</script>
</body>
</html>