vue.js - 如何从方法访问 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 方法可能是使用引用
<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;
}
当然,该示例有点荒谬,因为您知道项目的标题,但该原理适用于文本行的其他属性(例如属性、计算样式、类等)
推荐阅读
- amazon-web-services - 我无法从脚本 ssh 进入 ec2 实例
- javascript - 对象作为 React 子级无效:尝试显示我的帖子
- c# - Comobox 和 TextBox 在 ListView WPF C# 中无法正确显示
- go - 动态规划问题 - 扩展以找到所有可能的求和路径
- browser - 应用程序的浏览器支持和兼容性 - 有什么区别?
- python - 如何使用请求库在 python 中测试重试尝试
- azure - 公开 vnet 内的 Azure 容器实例的正确方法是什么?
- python - 尝试将抓取的数据添加到列表时仅返回一个值,Python
- azure - Azure Purview 不为从 blob 存储读取的平面文件提供架构
- amazon-web-services - 在 AWS Systems Manager 中删除 Automation Runbook 执行