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

标签 javascript arrays vue.js vuejs2

我创建了一个表,并在表中循环访问一个对象数组。

    <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 属性从 false 更改为 true。

这是 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,
}, ...]

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

关于javascript - 如何在vue中单击按钮时从数组中获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69615773/

相关文章:

java - 如何在 Java 中用数组初始化 vector ?

javascript - JS : mapping an array inside a push

vue.js - Cypress 与 Istanbul 尔不生成代码覆盖率报告

javascript - 如何通过函数更改对象

Javascript for..in 遍历参数 ie.for(arg in arguments) 在 IE8 中不起作用,但在 Chrome 8 中有效

javascript - 如何下载本地数组或添加到postgres数据库

javascript - 数组分配后Vue中的无限更新循环

javascript - Vue.js - 如何在 v-for 子组件中获取最后一个子引用

javascript - 滑出和滑入菜单边栏 html, css

javascript - 更改 route 标记的默认图标