[英]Pass loop variable as function parameter in HTML <input> onclick attribute with vue.js
I wanted to create a simple todo list in vue.js
to get myself comfortable with it. 我想在vue.js
创建一个简单的待办事项列表 ,以使自己适应它。
Now, I have placed a remove button after each item. 现在,我在每个项目之后都放置了一个删除按钮。 For that purpose, I have added a remove()
function in javascript with a parameter id
which is the id of the todo list item as well as onclick
attribute with the button. 为此,我在javascript中添加了带有参数id
的remove()
函数,该参数id
是待办事项列表项的id以及带有按钮的onclick
属性。 But the problem is I cannot find a way to pass item (loop variable created using v-for) id
as a parameter to remove()
function inside onclick
attribute. 但是问题是我找不到一种将项目(使用v-for创建的循环变量) id
作为参数传递给onclick
属性内的remove()
函数的方法。
So, far my script looks like this... 所以,到目前为止,我的脚本看起来像这样...
HTML 的HTML
...
<ul>
<li v-for="item in items">
{{ item.label }}
<input type="button" value="x" onclick="app.remove(item.id)">
<!-- item.id does not work -->
</li>
<li>
<input type="text" v-model="new_item" onkeypress="app.input_keydown(event)">
<input type="submit" value="+ Add" onclick="app.add()">
</li>
</ul>
...
JS JS
...
data: {
items: [
{id: 1, label: "One"},
{id: 2, label: "Two"},
{id: 3, label: "Three"},
{id: 4, label: "Four"},
],
add: function() {
// let item = prompt("Add Item", "New Item");
if (app.new_item) {
app.items.push(app.new_item);
}
},
remove: function(id) {
for (index in app.items) {
if (app.items[index].id == id) {
app.items.splice(index, 1);
}
}
},
}
...
And my simple todo list looks like this... 我的简单待办事项清单如下所示:
Also, I would like to know if in case I have to pass a loop variable in any HTML attribute, how would I do that? 另外,我想知道是否必须在任何 HTML属性中传递循环变量,我该怎么做?
you have to use Vue.js special event handlers instead of html one. 您必须使用Vue.js特殊事件处理程序,而不是html处理程序。 onclick="app.remove(item.id)"
should be @click="remove(item.id)"
. onclick="app.remove(item.id)"
应该是@click="remove(item.id)"
。
also you have to extract add
and delete
methods to methods
property. 您还必须将add
和delete
方法提取到methods
属性。 They can not be in data
. 它们不能包含在data
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.