当前位置:   article > 正文

elementUI 的 table 表格改变数据不更新问题_element table 改了数组值,没变化

element table 改了数组值,没变化

预期效果:点击输入框旁边的图标,输入框变为可输入状态;这里控制输入的 editable 字段不是 data 原有的属性,也不是 data 赋值时就存在的字段。
在这里插入图片描述
问题原因:在 Vue 实例创建时,以及 data 赋值时 editable 并未声明,因此就没有被Vue转换为响应式的属性,自然就不会触发视图的更新。

解决方法:

1、给 data 赋值前把 editable 属性添加到数组里

这里就不贴代码了,大概思路就是:获取到列表信息之后缓存在一个临时数组里(不可以是 data 里面定义好的对象),循环遍历列表信息,给每一条数据都添加一个属性 editable 值为 false,然后再把处理过的列表信息赋值给 data 。

2、使用:key 或者 v-if

修改绑定在 table 上面的 key 值,可以触发 table 的重新渲染,这样就可以把修改后的 data 在表格里面更新渲染。

<el-table :data="data" :key='num' stripe border>
	<el-table-column align="center" label="字段中文名称">
		<template slot-scope="scope">
    		<div style="display: flex;">
    			<el-input :disabled='!scope.row.editable' style="margin-right: 10px;"></el-input>
    			<el-button @click='changeEdit(scope.row)' type='text' icon="el-icon-edit-outline"></el-button>
    		</div>
    	</template>
    </el-table-column>
</el-table>
export default{
	data(){
		return{
			num:0,
			data:[]
		}
	},
	methods:{
		changeEdit(row){
			//每次点击图标 key 自动加一
			row.editable = true;
			num++;
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

这种方法有一个问题:给 table 添加一个默认高度,这个时候数据比较多的话会出现滚动条;当滚动条拉到下面,点击图标让对应的输入框可编辑,同时触发 table 渲染,滚动条会回到顶部,想查看被操作的输入框需要重新把滚动条拉到最下面;这样体验非常不好。如果有这样的场景推荐使用下面的方法。

3、使用 $set

$set 可以让动态的给 data 添加响应式的属性,让 editable 变为响应式的,就可以直接触发页面更新。

<el-table :data="data" stripe border>
	<el-table-column align="center" label="字段中文名称">
		<template slot-scope="scope">
    		<div style="display: flex;">
    			<el-input :disabled='!scope.row.editable' style="margin-right: 10px;"></el-input>
    			<el-button @click='changeEdit(scope.$index,scope.row)' type='text' icon="el-icon-edit-outline"></el-button>
    		</div>
    	</template>
    </el-table-column>
</el-table>
export default{
	data(){
		return{
			num:0,
			data:[]
		}
	},
	methods:{
		changeEdit(index,row){
			row.editable = true;
        	this.$set(this.data,index,row);
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

根据上面的方法延伸 :当 vue 能够检测到数组的变化,触发更新。

changeEdit(index,row){
	row.editable = true;
    this.data.splice(1,0);
}
  • 1
  • 2
  • 3
  • 4

方法远远不止上面这些,有其他想法的欢迎留言交流!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/107596?site
推荐阅读
相关标签
  

闽ICP备14008679号