我有一个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属性并将文本附加到项删除按钮中。
发布于 2018-05-27 21:23:25
传统的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;
}当然,这个例子有点荒谬,因为您知道项目的标题,但是这个原则适用于文本行的其他属性(例如属性、计算样式、类等)。
https://stackoverflow.com/questions/50556500
复制相似问题