vue3
<template><input type="checkbox" v-model="selectAll" />全选<ul><li v-for="item in list" :key="item.id">{{ item.value }} <input type="checkbox" v-model="item.check" /></li></ul>
</template>
<script>
import { computed, reactive } from '@vue/reactivity'
export default {setup () {const list = reactive([{id: 1,value: 15,check: false},{id: 2,value: 78,check: false},{id: 3,value: 63,check: false},{id: 4,value: 92,check: false},{id: 5,value: 38,check: false}])// computedconst selectAll = computed({get () {return list.every(item => item.check)},set (status) {console.log(status)list.forEach(item => { item.check = status })}})return { list, selectAll }}
}
</script>
vue2
<template><div><!-- 全选控制框 --><input type="checkbox" v-model="selectAll" />全选<!-- 列表 --><ul><li v-for="item in list" :key="item.id">{{ item.value }} <input type="checkbox" v-model="item.check" /></li></ul></div>
</template>
<script>
export default {data () {return {list: [{id: 1,value: 12,check: true},{id: 2,value: 45,check: false},{id: 3,value: 78,check: false},{id: 4,value: 96,check: false}]}},computed: {selectAll: {get () {return this.list.every(item => item.check)},set (state) {console.log(state)this.list.forEach(item => { item.check = state })}}}
}
</script>