简体   繁体   中英

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.

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. 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.

So, far my script looks like this...

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

And my simple todo list looks like this...

vue.js中的简单待办事项列表

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?

you have to use Vue.js special event handlers instead of html one. onclick="app.remove(item.id)" should be @click="remove(item.id)" .

also you have to extract add and delete methods to methods property. They can not be in data .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM