elementUI table组件默认选中行

<template>
  <el-table
    ref="multipleTable"
    :data="tableData"
    @row-click="handleRowChange">
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      width="120">
    </el-table-column>
  </el-table>
  <div style="margin-top: 20px">
    <el-button @click="saveData">保存修改</el-button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        defaultValue:['2', '3', '4'],
        tableData:[],
        remoteData: [{
          uid: '1',
          name: '王小虎',
        }, {
          uid: '2',
          name: '李四',
        }, {
          uid: '3',
          name: '张三',
        }, {
          uid: '4',
          name: '陈龙',
        }, {
          uid: '5',
          name: '周涛',
        }, {
          uid: '6',
          name: '刘文',
        }, {
          uid: '7',
          name: '于汉',
        }]
      }
    },

    methods: {
      handleRowChange(row) {
        this.$refs.multipleTable.toggleRowSelection(row)
      },
      loadData() {
        const self = this
        self.tableData = this.remoteData
        self.$nextTick(() => {
          self.tableData.forEach(function(item, idx) {
            if (self.defaultValue.indexOf(item.uid) >= 0) {
              self.$refs.multipleTable.toggleRowSelection(item, true)
            }
          })
        })
      },
      saveData() {
        const self = this
        self.defaultValue = []
        self.$refs.multipleTable.selection.forEach(function(item) {
          self.defaultValue.push(item.uid)
        })
        console.log(self.defaultValue)
      }
    },

    mounted() {
      this.loadData()
    }
  }
</script>

 

重点,不使用  selection-change  事件
 

如果在selection-change中给我们要提交的数据 defaultValue 赋值,那表格初始数据的选中状态永远也不会如你所想。

 我们只在点击保存修改的时候,重新获取已选中的数据,然后将需要的数据提取并赋值给defaultValue进行提交即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值