使用vue.js将循环变量作为函数参数传递到HTML <input /> onclick属性中

时间:2018-02-10 17:19:01

标签: javascript html html5 vue.js

我想在vue.js中创建一个简单的待办事项列表,让自己感觉很舒服。

现在,我在每个项目后面都放了一个删除按钮。为此,我在javascript中添加了remove()函数,参数id是todo列表项的id以及带有按钮的onclick属性。但问题是我无法找到一种方法将项目(使用v-for创建的循环变量)id作为参数传递给remove()属性中的onclick函数。

所以,我的脚本看起来很像......

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

...
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);
            }
        }
    },
}
...

我的简单待办事项列表如下所示......

Simple Todo List in vue.js

此外,我想知道如果我必须在任何 HTML属性中传递循环变量,我该怎么做?

1 个答案:

答案 0 :(得分:2)

你必须使用Vue.js特殊事件处理程序而不是html。 onclick="app.remove(item.id)"应为@click="remove(item.id)"

您还需要将adddelete方法提取到methods属性。它们不能在data