首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从方法访问vue重复项键

如何从方法访问vue重复项键
EN

Stack Overflow用户
提问于 2018-05-27 21:06:03
回答 1查看 73关注 0票数 0

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

代码语言:javascript
复制
<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密码。

代码语言:javascript
复制
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属性并将文本附加到项删除按钮中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-27 21:23:25

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

代码语言:javascript
复制
<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>

在代码中

代码语言:javascript
复制
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;
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50556500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档