需求
点击按钮弹出修改的对话框
出现的bug
在点开一个按钮之后,不做操作,关闭对话框,再点开另一个按钮,发现这一行的数据被改变了
具体如下
造成的原因
原因一:我在给弹出的对话框中赋值时,是浅拷贝,导致对话框中的数据源与table中的数据源是同一个数据源,修改对话框中的数据就是修改table中的数据
原因二:resetFields仅仅是将字段重置为初始值,并不是将数据清除。上图中第一次绑定的数据是1,所以表单的初始数据就是1,在第二次点击又关闭时,会触发resetFields方法,将对话框中的数据重置为初始值1,又因为是浅拷贝,所以会影响表格中的数据
官网介绍
这里可以看见是不是将数据清空,是初始值
解决方法(待定)
方法一: 使用 this.$nextTick
https://blog.csdn.net/gujian_peachblossom/article/details/117254326
方法二:仅仅拷贝值
this.editForm.username = tableData.username
完整代码,可直接赋值运行
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.4.5/theme-chalk/index.css">
</head>
<body>
<div id="id">
<h1>使用template调用函数</h1>
<el-table :data="userList" border style="width: 100%">
<el-table-column prop="username" label="姓名" width="180"></el-table-column>
<!-- 删除改良操作 -->
<el-table-column label="操作" width="190">
<template scope="scope">
<el-button type="primary" @click="showEditUser(scope.row)" size="mini">点击修改</el-button>
</template>
</el-table-column>
</el-table>
<!-- 虚假的对话框 -->
<el-dialog title="修改用户信息" :visible.sync="dialogEditUserVisible" width="50%" @close="closeEditDialog">
<el-form :model="editForm" ref="editUserFormRef" label-width="70px" class="demo-ruleForm">
<el-form-item label="用户名" prop="username">
<el-input v-model="editForm.username"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogEditUserVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogEditUserVisible = false">确 定</el-button>
</span>
</el-dialog>
</div>
</body>
<!-- 2.5.2 -->
<!-- <script src="https://cdn.staticfile.org/vue/2.5.2/vue.js"></script> -->
<script src="https://cdn.staticfile.org/vue/2.6.11/vue.js"></script>
<script src="https://cdn.staticfile.org/element-ui/2.4.5/index.js"></script>
<script>
new Vue({
el: '#id',
data() {
return {
userList: [{ username: 1 }, { username: 2 }, { username: 3 }, { username: 4 }, { username: 5 },],
editForm: {},
dialogEditUserVisible: false
};
},
methods: {
showEditUser(tableData) {
console.log(tableData);
// 这里是一个浅拷贝
this.editForm = tableData
this.dialogEditUserVisible = true
},
// 错误根源
closeEditDialog() {
// 就是因为是浅拷贝,所以this.editForm 与 tableData指向的是同一个对象,所以修改this.editForm就是在修改tableData指向的对象, 而tableData是通过tamplate中的方法传递过来的,所以tableData指向的数据其实是table中的数据
// 所以table中的数据才会改变
this.$refs.editUserFormRef.resetFields()
},
},
})
</script>
</html>