用vue写一个复选框全选和反选
时间: 2024-05-30 16:16:14 浏览: 104
<template>
<div>
<label>
<input type="checkbox" v-model="checkAll" @change="checkAllFn">全选
</label>
<label v-for="(item, index) in list" :key="index">
<input type="checkbox" v-model="item.checked" @change="selectFn"> {{ item.name }}
</label>
<button @click="reverseSelect">反选</button>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: '选项1', checked: false },
{ id: 2, name: '选项2', checked: false },
{ id: 3, name: '选项3', checked: false },
{ id: 4, name: '选项4', checked: false },
],
checkAll: false,
};
},
methods: {
checkAllFn() {
this.list.forEach((item) => {
item.checked = this.checkAll;
});
},
selectFn() {
let allChecked = true;
this.list.forEach((item) => {
if (!item.checked) {
allChecked = false;
}
});
this.checkAll = allChecked;
},
reverseSelect() {
this.list.forEach((item) => {
item.checked = !item.checked;
});
this.checkAll = !this.checkAll;
},
},
};
</script>
阅读全文