shayloyuki

科技是第一生产力

 

el-table 高亮行:只有设置表格数据才生效

需求:

  1. 表格若有数据,则默认高亮第一行。
  2. 之前高亮的行,若在查询结果列表中,则保持高亮不变;反之,则高亮第一行。

解决办法

需求 1 很容易实现:

  created() {
    // 默认高亮第一行
    if (this.libTable.length) {
      this.selectRow(this.libTable[0])
    }
  },
  methods: {
      // 高亮行
    selectRow(row) {
      this.$nextTick(() => {
        this.$refs.libTable.setCurrentRow(row, true)
        this.currentRow = row
      })
    },
  }

针对需求 2:监听搜索框,内容改变则调用搜索接口,把新的结果赋值给 表格数据。

因为每次表格数据都会更新,所以原来的高亮行会消失,若想保持高亮行不变,则需要继续高亮该行,

因此需要监听表格数据,能否在表格中找到原来的高亮行,能找到就高亮它;反之则高亮第一行。

  watch: {
    // 监听搜索框
    'queryParams.name': {
      handler(newVal) {
        this.queryParams.pageNum = 1
        this.loadSysLibList()
      }
    },
    // 监听表格数据:若高亮行存在,则高亮,反之高亮第一行
    'libTable': {
      handler(newVal) {
        if (!newVal.length) return
        const target = newVal.find(ele => ele.name === this.currentRow.name)
        if (target) {
	 // this.selectRow(this.currentRow) // 高亮不生效
          this.selectRow(target)
        } else {
          this.selectRow(this.libTable[0])
        }
      },
      deep: true      
    }
  },
  methods: {
      // 加载系统库列表
    async loadSysLibList() {
      this.loading = true
      const data = await sysLibList(this.queryParams)
      if (data.code === 200) {
        this.total = data.data.total
        this.libTable = data.data.rows
        this.loading = false
      }
    },
  }

如果 this.selectRow(this.currentRow) 则高亮不生效。

但写为 this.selectRow(target) 高亮生效。

原因:this.currentRow 来源是之前的表格数据,不是目前最新的表格数据。而 el-table 的高亮方法要求必须是当前的表格数据,即使它们的值一样,但是内存地址不同。(打个比方:两套房子内部一摸一样,但这就是两套房子不是同一套房子)。

    // 获取选中行
    onRowClick(row) {
      this.currentRow = row
    },

image

把它俩打印出来,内部数据有些微差异:

image

posted on 2022-08-25 14:38  shayloyuki  阅读(1201)  评论(0编辑  收藏  举报

导航