vue3
<template>
<div>
<el-checkbox label="全选" v-model="allChecked"></el-checkbox>
<el-checkbox
v-for="(item, index) in arr"
:key="index"
v-model="item.checked"
:label="item.name"
size="large"
/>
</div>
</template>
<script>
import { computed, ref } from "vue";
export default {
setup() {
const arr = ref([
{
name: "选项一",
checked: true,
},
{
name: "选项二",
checked: true,
},
{
name: "选项三",
checked: true,
},
{
name: "选项四",
checked: false,
},
]);
const allChecked = computed({
get() {
return arr.value.every((item) => item.checked);
},
set(newVal) {
arr.value.forEach((item) => (item.checked = newVal));
},
});
return { arr, allChecked };
},
};
</script>
vue2
<template>
<div id="app">
<el-checkbox
label="全选"
v-model="allChecked"
></el-checkbox>
<el-checkbox
v-for="(item, index) in arr"
:key="index"
v-model="item.checked"
:label="item.name"
size="large"
/>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
arr: [
{
name: '选项一',
checked: true
},
{
name: '选项二',
checked: true
},
{
name: '选项三',
checked: true
},
{
name: '选项四',
checked: false
}
]
}
},
computed: {
allChecked: {
// 小选影响全选
get () {
return this.arr.every((item) => item.checked)
},
// 全选影响小选
set (newVal) {
this.arr.forEach(item => {
item.checked = newVal
})
}
}
}
}
</script>
|