zoukankan      html  css  js  c++  java
  • 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
          },
          set (value) {
            this.list.forEach(function (item) {
              item.status = value
            })
          }
        }
      }

      

  • 相关阅读:
    Hash大法
    最小表示法
    KMP算法题集
    分块总结
    2018 雅礼国庆集训
    二分图总结
    贪心总结
    Tire树总结(模板+例题)
    工具类文章合集
    网文胡乱汇总
  • 原文地址:https://www.cnblogs.com/wuqilang/p/14886406.html
Copyright © 2011-2022 走看看