起因:
产品:需求要一个表单,表单中的数据点击可以进行修改
我:可以,听起来好像没什么问题。
然后我就开始了摸代码模式......
代码如下
<template> <el-table :data="tableData" border height="580" style="width: 100%" scroll :header-cell-style="{ background: '#f7f7fa', color: '#000', }" > <el-table-column type="index" label="序号" width="50" :key="1" :fixed="'left'"></el-table-column> <el-table-column v-for="(item, index) in tableColumnList" :prop="item.prop" :label="item.label" :key="index + 2" width="170px"> <template slot-scope="scope"> <template v-if="item.prop == 'first'"> <div style="height: 100%; width: 100%" @click="editClick(scope.row)" v-if="!scope.row['isShow']"> {{ scope.row[item.prop] }} </div> <el-input v-if="scope.row['isShow']" :ref="`input${scope.row.id}`" type="number" v-model="scope.row[item.prop]"></el-input> </template> <span v-else style="color: black"> {{ scope.row[item.prop] }} </span> </template> </el-table-column> </el-table></template><script>export default { name: "MainPage", props: {}, data() { return { tableData: [ { id: 111, first: "200", second: "200", }, { id: 222, first: "330", second: "450", }, ], tableColumnList: [ { prop: "first", label: "测试数据1", }, { prop: "second", label: "测试数据2", }, ], }; }, methods: { editClick(row) { row.isShow = true; this.tableData = JSON.parse(JSON.stringify(this.tableData)); this.$nextTick(() => { console.log(this.$refs); }); }, },};</script><style lang="less" scoped></style>
代码运行之后,点击prop:'first'这一列的数据,输出结果如下:
然后通过ref对这个输入框的操作就不生效了
起初以为是因为直接修改row里的数据,数据发生变化之后,导致dom又重新渲染了一遍,从而导致了有多个同名ref,于是作出了如下修改:
editClick(scope) { let temp = JSON.parse(JSON.stringify(this.tableData)); temp[scope.$index].isShow = true this.tableData = temp this.$nextTick(() => { console.log(this.$refs); }); },
输出结果如下:
嗯,没错,没变
然后猜想,如果是重新渲染的话,如果添加了key之后,是不是就好了,然后就给input框添加上了key,:key="`input${scope.row.id}`",
嗯,结果还是没变
于是我便准备使用cv大法,去某度某乎看看
出乎意料,没浏览到有用的信息,不过在搜索过程中,看到了别人的一个问题:
点进去看了一眼,往下扒拉扒拉发现了这个评论:
嗯?fixed,渲染了两个table?进而又去看了眼
就是说,是的,el-table如果使用fixed的话,就会渲染多个table,然后,检查了下代码:
<el-table-column type="index" label="序号" width="50" :key="1" :fixed="'left'"></el-table-column>
给fixed属性去掉试试:
好家伙,可算让我抓住你了;但是吧。。。fixed不用又不行,用了又有问题,怎么办?
直接使用这个同名多个ref,然后遍历进行相同操作?
emm,想不到好办法,有大佬给支支招吗?