首页 > 解决方案 > 如何在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>

我想要的是在编辑按钮单击时,我想将 contenteditable 属性从 false 更改为 true。

这是数据()的代码

<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”更改属性,但是当我控制台它时,它会在按钮单击时返回最后一个数组

标签: javascriptarraysvue.js

解决方案


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

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

然后将contenteditable td属性绑定到这些值(而不是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]; 
}

推荐阅读