Search code examples
javascriptvue.jsmethodsvue-componentv-for

increment only on a number on a single <li> in a for with VueJs


I want that in my v-for, when I click the UP button, the li which is linked to the button increases his State by +1.

Here is a bit of my code:

Vue.component('app', {
    data: function () {
        return {
            messages: '',
            state: 0,
            id: 0,
            todo: [],
            columns: ["todo", "doing", "done"],
        }
    },

    methods: {
        upElement: function (id) {
            this.id
            this.state++;
        },
        removeElement: function (key) {
            this.todo.splice(key, 1);
        },
    },

    template: `
        <ul>
            <li v-if="state === 0" v-for="(item, key) in todo" v-bind:messages="todo.messages + todo.state + todo.id" :key="item.id" v-bind:id="key">
                <span>{{item.messages}}</span></br>
                <button v-on:click="upElement">UeP</button>
                <button v-on:click="removeElement(key)">remove</button>
            </li>
        </ul>=
    `,
})

I wanted to put an id to target the li but it does not work


Solution

  • You can pass the item object directly to your upElement function and modify the state property.

    Vue.component('app', {
        data: function () {
            return {
                messages: '',
                state: 0,
                id: 0,
                todo: [],
                columns: ["todo", "doing", "done"],
            }
        },
    
        methods: {
            upElement: function (item) {
                item.state++;
            },
            removeElement: function (key) {
                this.todo.splice(key, 1);
            },
        },
    
        template: `
                        <ul>
                            <li v-if="state === 0" v-for="(item, key) in todo" v-bind:messages="todo.messages + todo.state + todo.id" :key="item.id" v-bind:id="key">
                                <span>{{item.messages}}</span></br>
                                <button v-on:click="upElement(item)">UeP</button>
                                <button v-on:click="removeElement(key)">remove</button>
                            </li>
                        </ul>=
        `,
    })