1. 程式人生 > >Vue實現全選功能

Vue實現全選功能

orm 點擊 fault highlight index otto vuejs tom guid

https://cn.vuejs.org/v2/guide/forms.html

<template>
  <div class="hello">
    <input type="checkbox" value="全選" style="margin-bottom:20px;" v-model="selectAll">全選
    <span @click="canCleAll">取消</span>
    <div>
      <template v-for="item of list">
        <!-- 多個復選框,綁定到同一個數組 -->
        <!-- v-model綁定到數組checkedList,當checkbox選中時,input的value值,會push到數組checkedList中 -->
        <input type="checkbox" :key="item.index" :value="item.movieUrl" v-model="checkedList" />{{item.movieName}}
      </template>
    </div>
  </div>
</template>

<script>
export default {
  name: ‘HelloWorld‘,
  data() {
    return {
      list: [
        {
          movieName: ‘電影1‘,
          movieUrl: ‘xxxxx‘
        }, {
          movieName: ‘電影2‘,
          movieUrl: ‘xxxxx‘
        }, {
          movieName: ‘電影1‘,
          movieUrl: ‘xxxxx‘
        },
        {
          movieName: ‘電影2‘,
          movieUrl: ‘xxxxx‘
        }
      ],
      checkedList: []
    }
  },
  computed: {
    selectAll: {
      get() {
        return this.checkedList.length === this.list.length
      },
      // 點擊全選,取消全選是出發,選中時,value值為true,取消選中時,value值為false
      set(value) {
        if (value) {
          // 方法一 forEach遍歷,push到checkedList中
          // let that = this
          // this.checkedList = []
          // this.list.forEach(item => {
          //   that.checkedList.push(item.movieUrl)
          // })
          // 方法二,map遍歷
          this.checkedList = this.list.map(item => {
            return item.movieUrl
          })
          // console.log(this.checkedList)
        } else { // 取消選中。重置checkedList數據。
          this.checkedList = []
        }
      }
    }
  },
  methods: {
    canCleAll() {
      this.checkedList = []
    }
  }
}
</script>

<style scoped>
</style>

Vue實現全選功能