Vue中点击按钮如何获取数组对应对象并修改单元格contenteditable属性
问题原因
你在v-for循环中给所有行的位置td绑定了同名reftxtLocaton,Vue会将所有匹配的DOM元素收集为一个数组存到this.$refs.txtLocaton中,你没有传入当前点击行的下标,自然无法定位到对应行的元素,这就是你每次只能拿到最后一项的原因。另外直接操作DOM不符合Vue数据驱动的设计理念,更推荐通过数据控制属性的方式实现需求。
最优实现方案(数据驱动)
不需要操作DOM,通过绑定contenteditable属性到数组项的状态字段即可:
1. 模板修改
<table class="table table-striped" v-if="bins.length > 0"> <thead> <tr> <th scope="col">#</th> <th scope="col">Location</th> <th scope="col" class="text-end">Action</th> </tr> </thead> <tbody> <tr v-for="(bin, index) in bins" :key="index"> <th scope="row">{{index + 1}}</th> <!-- 把contenteditable绑定到当前行的editable状态 --> <td :contenteditable="bin.editable" v-text="bin.binlocation"></td> <td class="text-end"> <div class="action-btn"> <!-- 点击时传入当前行下标 --> <button @click="btnEdit(index)"><fa icon="edit" /> Edit</button> <button><fa icon="trash" /> Delete</button> </div> </td> </tr> </tbody> </table>
2. 逻辑代码修改
<script> export default { data(){ return{ bins:[ { binlocation: '11 Garden Block, New City', editable: false // 新增编辑状态字段,默认不可编辑 }, { binlocation: 'Ali Towers, Lahore', editable: false }, { binlocation: 'The Mall Road', editable: false } ] } }, methods:{ btnEdit(index){ // 直接修改对应行的编辑状态即可 this.bins[index].editable = true } } } </script>
如果你坚持用ref实现
只需要在点击时传入当前行下标,取对应下标的ref元素修改属性即可:
methods:{ btnEdit(index){ this.$refs.txtLocaton[index].contentEditable = true } }
模板中修改按钮点击事件为@click="btnEdit(index)"即可。
内容的提问来源于stack exchange,提问作者Muhammad Ameen Sheikh
相关产品推荐
相关产品推荐

