1.需求:

当用户拖动表格的表头可以拖动列的宽度,并且记住拖动后的宽度。

2.逻辑思路

利用localStroage的本地存储功能,将拖动后的宽度存储到本地,再次进入页面的时候就会调用created,并获取本地存储的宽度,然后设置上宽度

3.实现

<template>
  <el-table
    ref="tableRef"
    border
    :data="tableData"
    @header-dragend="changeColWidth"
  >
    <el-table-column
      v-for="column in tableColHead"
      :key="column.columnTitle"
      :prop="column.columnName"
      :label="column.columnTitle"
      :width="column.width"
    >
      <template slot-scope="{row}">
        {{ row[column.columnName] }}
      </template>
    </el-table-column>
  </el-table>
</template>

<script>

export default {
  name: 'Test',
  data() {
    return {
      // 列表表头json
      tableColHead: [
        {
          'columnName': 'nameColumn',
          'columnTitle': '姓名',
          'width': '',
          'align': 'left',
          'isShow': true
        },
        {
          'columnName': 'ageColumn',
          'columnTitle': '年龄',
          'width': '400px',
          'isShow': true
        },
        {
          'columnName': 'sexColumn',
          'columnTitle': '性别',
          'width': '150px',
          'isShow': true
        }
      ],
      // 列表数据json
      tableData: [
        {
          nameColumn: '张三',
          ageColumn: 16,
          sexColumn: '男'
        },
        {
          nameColumn: '李四',
          ageColumn: 18,
          sexColumn: '女'
        }
      ]
    }
  },
  created() {
    // 页面初始化获取存储的json
    if (localStorage.getItem('applyTableColWidth')) {
      this.tableColHead = JSON.parse(localStorage.getItem('applyTableColWidth'))
    }
  },
  methods: {
    // 拖动表头改变列的宽度的时候触发的事件
    changeColWidth(newWidth, oldWidth, { property }) {
      const applyTableColWidth = this.tableColHead.map(item => {
        if (item.columnName === property) {
          item.width = newWidth
        }
        return item
      })
      // 存储列宽改变后的json
      localStorage.setItem('applyTableColWidth', JSON.stringify(applyTableColWidth))
    }
  }
}
</script>
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐