vue 实现列表全选

vue yekong 144℃

html

<div class="userlist">
        <div class="userlisthead">
          <div class="userlistheaditem" style="flex: 1">
            <div class="selectAll cur" @click="getselected">
              <div class="select" :class="{selected:selectedAll}"></div>
              <em>全选</em>
            </div>
          </div>
        </div>
        <div class="userlistbody scroll">
          <div class="userlistbody_list" v-for="(item,index) in list" :key="index">
            <div class="userlistbodyitem" style="flex: 1">
              <div class="select cur" @click="selected(index)" :class="{selected:item.selected}"></div>
            </div>
          </div>
        </div>
      </div>

js

  data () {
    return {
      total: 0,
      selectedAll: false,
      list: [],
    }
  },
mounted () {
    this.listUsers()
  },
  methods: {
    // 全选
    getselected () {
      this.selectedAll = !this.selectedAll
      this.getselectedCheck()
    },
    getselectedCheck () {
      var that = this
      var data = that.list
      for (var i = 0; i < data.length; i++) {
        data[i].selected = this.selectedAll
      }
      that.list = data
    },
    // 判断是否全选
    getIsSeletedAll () {
      var data = this.list
	  this.selectedAll = false
      var num = 0
      for (var i = 0; i < data.length; i++) {
        if (data[i].selected) {
          num = num + 1
        }
      }
      if (num === this.list.length && this.list.length > 0) {
        this.selectedAll = true
      }
    },
    // 选择
    selected (e) {
      this.list[e].selected = !this.list[e].selected
      // 更新列表
      this.$forceUpdate()
      this.getIsSeletedAll()
    },
    listUsers () {
      var that = this
      listUsers({}).then(res => {
        const { code } = res
        if (code === 0) {
          that.list = res.data.list
          var data = that.list
          // 给列表字段添加selected字段
          for (var i = 0; i < data.length; i++) {
            data[i].selected = false
          }
          that.list = data
          console.log(that.list)
        }
      })
    },
  },
喜欢 (0)