el-table 数据刷新与滚动条定位

文章讲述了在Vue.js项目中,利用el-table组件进行数据展示时,如何通过设置key值来实现表格数据更新。同时,当表格数据更新后,通过延时函数和滚动条定位方法,确保表格更新后能保持原来的滚动位置。涉及到的技术包括Vue的ref绑定、事件处理以及DOM操作。
摘要由CSDN通过智能技术生成

1、在el-table中设置key值,重新赋值表格数据之后,更新key值,达到动态更新效果

            <el-table
              v-show="workList.length > 0"
              ref="rw_table"
              :key="tableKey"
              :data="workList"
              tooltip-effect="dark"
              :cell-style="{fontFamily: `'黑体', Times, serif;`, fontSize: '16px', color: '#FFF', backgroundColor: '#30384F'}"
              :header-cell-style="{fontFamily: `'黑体', Times, serif;`, fontSize: '16px', color: '#FFF', backgroundColor: '#30384F'}"
              :row-style="{fontFamily: `'黑体', Times, serif;`, fontSize: '16px', color: '#FFF', backgroundColor: '#30384F'}"
              height="100%"
            >
              <el-table-column prop="name" label="名称" align="center" />
              <el-table-column prop="sequence" label="编号" align="center" />
            </el-table>
// 在tableData赋值的地方,顺便随机设置下key,页面就会刷新了
this.workList= workList
this.tableKey = Math.random()
setTimeout(() => {
    this.getTableScrollTop(index)
})

2、表格更新后用延时函数进行滚动条定位

getTableScrollTop(index) {
      const elTable = this.$refs['rw_table'].$el
      const scrollParent = elTable.querySelector('.el-table__body-wrapper')
      const box = document.getElementById('div').clientHeight
      // const containerTop = elTable.querySelector('.el-table__body').clientHeight // table-body的高度
      const targetHeight = elTable.querySelectorAll('.el-table__body tr')[index].clientHeight // 该行的高度
      let moveHeight
      /*超过显示范围,向下移动*/
      const num = Math.floor(box / targetHeight) - 1
      if (index >= num) {
        moveHeight = (index + 1 - num) * targetHeight
      }
      if (index === this.workList.length - 1) {
        moveHeight = 0
      }
      // console.log('index', index, 'lehgth', this.workList.length, 'box', box, 'num', num, 'moveHeight', moveHeight)
      /*每次都向下移动*/
      // if (index < this.workList.length - 1) {
      //   moveHeight = targetHeight * (index + 1)
      // } else {
      //   moveHeight = 0
      // }
      scrollParent.scrollTop = moveHeight
    }
    }

3、表格中有多选框

table-comp是对el-table的包装,

ref="elTable,设置滚动条位置使用

el-checkbox-group是多选的值,数组

el-col与el-checkbox组合是展示多选项

@change事件,保存滚动条位置,刷新表格key,更新表格

滚动条设置函数在update()中,        

setTimeout(() => {
            this.getTableScrollTop()
})

<div class="content">
    			<table-comp :column-list="columnList"
						:table-data="topologyList"
						:key="tableKey"
						ref="elTable"
			>

				<template  slot-scope="scopefx">
					{{ scopefx.scopefx.row.id}}
				</template>

				<template  slot-scope="scopefx">
					{{ scopefx.scopefx.row.name}}
				</template>

				<template slot="o" slot-scope="scopefx">
					<el-checkbox-group v-model="scopefx.scopefx.row.pip">
						<el-col v-for="item in pipeList"
								:key="item.code"
								:label="item.code"
								:span="4">
							<el-checkbox
								:label="item.code"
								@change = "changeTag">
								{{item.label}}
							</el-checkbox>
						</el-col>
					</el-checkbox-group>
				</template>
				<template  slot="op" slot-scope="scopefx">
					<el-checkbox-group v-model="scopefx.scopefx.row.mod">
						<el-col v-for="item in testModeList"
								:key="item.code"
								:label="item.code"
								:span="5">
							<el-checkbox
								:label="item.code"
						        :disabled = "item.isDeleted===1"
								@change = "changeTag">
								{{item.label}}
							</el-checkbox>
						</el-col>
					</el-checkbox-group>
				</template>
				<template slot="opera" slot-scope="scopefx">
					<el-button type="success" round @click="saveTopology(scopefx.scopefx.row)">保存</el-button>
					<el-button type="success" round @click="deleteTopology(scopefx.scopefx.row)">删除</el-button>
				</template>
			</table-comp>
</div>

js代码

export default {
	name: "topology",
	data() {
		return {
			tableKey: "",
			memoryScrollTop: '',
			dialogVisible: false,
			testModeList: [],
			topologyList: [],
			pipeList: [],
			columnList: [
				{
					prop: 'id',
					label: 'id',
					width: 50
				},
				{
					prop: 'name',
					label: '名称',
					width: 150
				},
				{
					prop: 'pip',
					label: '管子',
					slot: 'o',
					width: 500
				},
				{
					prop: 'mod',
					label: '测试模式',
					slot: 'op',
					width: 550
				},
				{
					label: '保存',
					prop: 'opera',
					slot: 'opera',
				}
			],
			form: {
				name: '',
				id: '',
				pipes: [],
				mode: []
			},
			rules: {
				name: [{required: true, trigger: 'change', message: '请输入名称'}],
				id: [{required: true, trigger: 'blur', message: '请输入id'}],
			},
		}
	},
	created() {
		this.getTestMode()
		this.getTopology()
		this.getPipeNums()
	},
	updated() {
		setTimeout(() => {
			this.getTableScrollTop()
		})
	},
	methods: {
		getTestMode() {
			commonService.getTestMode('topology-test-mode').then(result => {
				this.testModeList = result.data;
			});
		},
		getTopology() {
			commonService.getTopology().then(result => {
				this.topologyList =  result.data;
				this.topologyList.forEach(item => {
					item.mod = item.mode.map(number => number.toString());
					item.pip = item.pipes.map(number => number.toString());
				});
			});
		},
		saveTopology(row) {
			let obj = row;
			obj.mode = obj.mod.map(item=> Number(item)).sort();
			obj.pipes = obj.pip.map(item=> Number(item)).sort();
			let data = [];
			data.push(obj);
			commonService.updateTopology(data).then(result => {
				this.$message.success('保存成功')
				this.getTopology()
			});
		},deleteTopology(row){
			let obj = row;
			obj.isDeleted = 1;
			let data = [];
			data.push(obj);
			commonService.updateTopology(data).then(result => {
				this.$message.success('保存成功')
				this.getTopology()
			});
		},
		changeTag(){
			this.getTableScrollTop(true)
			this.tableKey = Math.random()
		},
		addTopology(){
			this.dialogVisible = true;
		},
		closeDialog(){
			this.form.id = '';
			this.form.name = '';
			this.form.pipes = [];
			this.form.mode = [];
			this.dialogVisible = false;
		},
		saveDialog(){
			this.$refs.form.validate((valid) => {
				if(valid){
					this.dialogVisible = false;

					let item = {
						id: Number(this.form.id),
						name: this.form.name,
						pipes:this.form.pipes,
						mode: this.form.mode,
						type: Number(this.form.id),
						tag: 'DEFAULT'
					}
					service.saveTopology(item).then(result => {
						this.$message.success('保存成功')
						this.getTopology()
					}).catch(err=>{
						this.$message.error(err)
					});
				}else {
					this.$message.info('请完善参数')
				}
			});
		},
		getPipeNums() {
			commonService.getTestMode('max-pipes').then(res => {
				let pipenum = 7;
				if (res.data.length > 0) {
					pipenum = Number(res.data[0].code);
				}
				for (let i = 0; i <= pipenum; i++) {
					this.pipeList.push({"code": i.toString(), "label": i.toString()})
				}
			});
		},
		getTableScrollTop( ifMemory = false ) {
			if ( !this.$refs['elTable'] ) return //不存在这个表格则返回
			let elTable = this.$refs['elTable'].$el
			if ( !elTable ) return
			let scrollParent = elTable.querySelector('.el-table__body-wrapper')
			if ( ifMemory ) {
				//保存
				this.memoryScrollTop = scrollParent.scrollTop //存下当前编辑行的ScrollTop
			} else {
				//跳转
				scrollParent.scrollTop = this.memoryScrollTop //跳转到存下编辑行的ScrollTop
			}
		}

	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值