如何在vue中单击按钮时从数组中获取对象



我创建了一个表,在表中循环遍历一个对象数组。

<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>
<td ref="txtLocaton" contenteditable="false" v-text="bin.binlocation"></td>
<td class="text-end">
<div class="action-btn">
<button @click="btnEdit"><fa icon="edit" /> Edit</button>
<button><fa icon="trash" /> Delete</button>
</div>
</td>
</tr>
</tbody>
</table>

我想要的是,在Edit按钮点击,我想改变contenteditable属性从假到真。

这是data() 的代码
<script>
export default {
data(){
return{
bins:[
{
binlocation: '11 Garden Block, New City',
},
{
binlocation: 'Ali Towers, Lahore'
},
{
binlocation: 'The Mall Road'
}
]
}
},
methods:{
btnEdit(){
console.log(this.$refs.txtLocaton)
}
}
}
</script>

我正在考虑使用ref更改属性,但当我控制它时,它正在返回按钮单击

上的最后一个数组

您可以将contenteditable键存储在bins数组中(最初是false?):

[{
binlocation: '11 Garden Block, New City',
contenteditable: false,
}, {
binlocation: 'Ali Towers, Lahore',
contenteditable: false,
}, ...]

然后将contenteditabletd属性绑定到这些值(而不是直接传递false):

<td ref="txtLocaton" :contenteditable="bin.contenteditable" v-text="bin.binlocation"></td>

和简单地切换值,你希望当"编辑"按钮按下:

<button @click="bin.contenteditable = !bin.contenteditable"><fa icon="edit" /> Edit</button>

<button @click="btnEdit(index)"><fa icon="edit" /> Edit</button>
btnEdit(index) {
this.bins[index] = !this.bins[index]; 
}

尝试下面的代码片段(您可以将index传递给您的方法并将contentitable属性绑定到data属性):

new Vue({
el: '#demo',
data(){
return{
bins:[
{binlocation: '11 Garden Block, New City',},
{binlocation: 'Ali Towers, Lahore'},
{binlocation: 'The Mall Road'}
],
editable: null
}
},
methods:{
btnEdit(index){
this.editable = index
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
.editable {
border: 2px solid violet;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<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>
<td ref="txtLocaton" :contenteditable="index === editable" :class="index === editable && 'editable'" v-text="bin.binlocation"></td>
<td class="text-end">
<div class="action-btn">
<button @click="btnEdit(index)"> Edit</button>
<button> Delete</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>

最新更新