element-ui的el-table在使用setCurrentRow无效问题

1,198 阅读1分钟

场景是加载好表格后需要默认第一行高亮

this.$nextTick(() => {
  this.$refs.table.setCurrentRow(this.dataList[0])
})

代码这样发现无效

查看源码

getRowClass(row, rowIndex) {
  let selection = this.store.states.selection;
  const classes = ['el-table__row'];
  if (this.table.highlightCurrentRow && row === this.store.states.currentRow) {
    classes.push('current-row');
  }

  if (this.table.highlightSelectionRow) {
    for (let i = 0; i < selection.length; i++) {
      if (objectEquals(row, selection[i])) {
        classes.push('selection-row');
      }
    };
  }

  if (this.stripe && rowIndex % 2 === 1) {
    classes.push('el-table__row--striped');
  }
  const rowClassName = this.table.rowClassName;
  if (typeof rowClassName === 'string') {
    classes.push(rowClassName);
  } else if (typeof rowClassName === 'function') {
    classes.push(rowClassName.call(null, {
      row,
      rowIndex
    }));
  }

  if (this.store.states.expandRows.indexOf(row) > -1) {
    classes.push('expanded');
  }

  return classes;
},

饿了么这里的判断是这两个全等,row === this.store.states.currentRowthis.dataList[0]和组件里的数据不是同一个引用地址,找到原因。

通过this.$refs.table.store.states.data可以获取到组件内的data值,this.store.states.currentRow的值是从这个data中获取的。

封装下

setCurrentRowHighlight(row) {
  const data = this.$refs.table.store.states.data || []
  const index = data.findIndex((o) => o[this.config.rowKey] === row[this.config.rowKey])
  const newRow = data[index]
  this.$refs.table.setCurrentRow(newRow)
},