效果:
一、通过watch监听和methods进行数据交互
DOM结构:
<template> <div id="app"> <ul> <li><input type="checkbox" v-model="allCheck" @click="handleAllCheck" />全选</li><br /> <li v-for="item in list" :key="item.id"> <input type="checkbox" v-model="item.status" />{{item.xueli}} </li><br /> </ul> </div> </template>
data:
data() { return { list: [ { id: 1, xueli: '小学', status: true }, { id: 2, xueli: '初中', status: false }, { id: 3, xueli: '高中', status: true }, { id: 4, xueli: '大学', status: true } ], allCheck: null } }
watch+methods:
watch: { list: { handler(newList) { this.allCheck = newList.every((item) => item.status === true) }, deep: true, immediate: true } }, methods: { handleAllCheck() { this.list.forEach((item) => { item.status = !this.allCheck }) } }
二、通过computed进行数据交互
DOM(全选按钮不需要点击事件):
<template> <div id="app"> <ul> <li><input type="checkbox" v-model="allCheck" />全选</li><br /> <li v-for="item in list" :key="item.id"> <input type="checkbox" v-model="item.status" />{{item.xueli}} </li><br /> </ul> </div> </template>
data中不需要定义allCheck变量,使用的是computed中定义的allCheck:
computed: { allCheck: { get () { const arr = this.list.filter((item) => !item.status) if (arr.length === 0) return true }, set (value) { this.list.forEach(function (item) { item.status = value }) } } }