vue全选和取消全选的实现方式(主要是理解computed中的set和get)

效果:

  

 

一、通过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
     // return
this.list.every(item => item.status)
      },
      set (value) {
        this.list.forEach(function (item) {
          item.status = value
        })
      }
    }
  }
复制代码

 

  

 

posted @   吴小明-  阅读(392)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示