当我有个element表格,想要做到点击编辑并保存时,我会想到这么做
<el-table
:data="userInformation"
:row-class-name="changeClassName">
<el-table-column
min-width="50"
label="用户名"
prop="username"
align="center"
sortable>
<template slot-scope="scope">
<span v-if="!scope.row.isShow"><el-tag type="success">{{scope.row.username}}</el-tag></span>
<el-input v-model="scope.row.username" v-if="scope.row.isShow"></el-input>
</template>
</el-table-column>
<el-table-column label="操作" align="center">
<template v-slot="scope">
<el-button type="text" @click="edit(scope.row)" v-if="!scope.row.isShow">编辑</el-button>
<el-button type="text" @click="deleteRow(scope.row)" v-if="!scope.row.isShow">删除</el-button>
<el-button type="text" @click="save(scope.row)" v-if="scope.row.isShow">保存</el-button>
<el-button type="text" @click="close(scope.row)" v-if="scope.row.isShow">取消</el-button>
</template>
</el-table-column>
</el-table>
我会想,点击编辑时,让el-input显示,span则隐藏,我在input和span中都加入了v-if判断isShow的值是true还是false,那么我在点击时修改isShow的值能不能让他生效呢
methods:{
edit(row){
row.isShow = true
},
}
试过之后,发现是不生效的,因为JavaScript的限制,vue某些时候无法检测到数组的值被修改,此时我们用到$set(Object, key, value),为什么是$set(Object, key, value)而不是VUE.set(Object, key, value)呢?因为我的vue版本是3.X以上的,$set(Object, key, value)是3.X以上版本所用的对象方法,而VUE.set(Object, key, value)是vue2版本所用的对象方法。所以,将$set(Object, key, value)加入到edit(row)方法中去:
methods:{
edit(row){
row.isShow = true
this.$set(this.userInformation, row.index, row)
},
}
在此补充一点,其中的row.index,以防初学者不知道怎么获取的,我在el-table中有绑定一个方法:row-class-name="changeClassName" element-ui官方有提到,是行的回调方法,它可以获取到rowIndex,所以我们只要在这个方法中,给数组添加一组数据就行,下面贴出代码:
changeClassName({row,rowIndex}){
row.index = rowIndex;
}