首页 > 解决方案 > 如何从方法访问 vue 重复项键

问题描述

我有一个 html 页面,它有一个表和一个使用 v-for 的迭代行:

<table id="app-4">
  <tr v-for="(item, index) in results" :key="item.id">
    <td>@{{ item.title }}</td>
    <td>
       <button v-on:click="deleteItem(index)">Delete</button>
    </td>
  </tr>
</table>

我有这个js代码。

var app4 = new Vue({
  el: '#app-4',
  data: {
    results: []
  },
  methods: {
    deleteItem: function (index) {
        this.results.splice(index,1);
        //Can I access item key and tr properties from here and the delete button
    }
  },
  mounted() {
    axios.get('api.list.url').then(response => {
        this.results = response.data;
    })
  }
});

在 deleteItem 函数中,我可以访问项目键和tr 属性并将文本附加到项目删除按钮。

标签: vue.jsvuejs2frontendv-for

解决方案


传统的 Vue 方法可能是使用引用

<table id="app-4">
  <tr v-for="(item, index) in results" :key="item.id" ref="rows">
    <td>@{{ item.title }}</td>
    <td>
       <button v-on:click="deleteItem(index)" ref="deleteButtons>
           Delete
       </button>
    </td>
  </tr>
</table>

并且在代码中

deleteItem: function (index) {
    this.results.splice(index,1);
    //Can I access item key and tr properties from here?

    // Yes, e.g. to get the text content of the first cell
    const text = this.$refs.rows[index].cells[0].textContent.trim();

    // And add it to the delete button text
    this.$refs.deleteButtons[index].textContent += " " + text;
}

当然,该示例有点荒谬,因为您知道项目的标题,但该原理适用于文本行的其他属性(例如属性、计算样式、类等)


推荐阅读