1. 程式人生 > 其它 >vue全選和取消全選的實現方式(主要是理解computed中的set和get)

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
        })
      }
    }
  }