CometZ
CometZ

Reputation: 115

How do I delete a clicked item within an array with Vuejs?

The issue here is that my splice() method doesn't seem to work at all. This is just a simple To-Do app, and I want to delete a specific task by clicking a button. I've already tried the solutions from a more popular Stack Overflow thread, but they doesn't seem to work for me. The items do get deleted, but only the last ones, not the one I click

<template>
    <div class="task-wrapper">
        <p id="task-counter"> Tasks Today: {{  taskArr.length  }} </p>
        <div class="task-counter-wrapper">                 
            <!-- ? Render if there are no tasks available: -->
            <div class="empty-msg"
                 v-if="taskArr.length == 0"
            >
                <p>Start by adding a New Task!</p>
            </div>

            <div class="task-list" 
                 v-for="(task, idx) in taskArr"
                 :key="idx">

                <div class="list-item">

                    <div class="container">
                        <input class="list-checkbox" type="checkbox">
                        ({{ idx + 1}}) {{ task.name}}
                    </div>

                    <div class="item-actions">
                        <button class="edit-item btn"
                                v-on:click="editItem()"
                        >
                            <img class="icon" src="./Images/editing.png">
                        </button>

                        <button class="delete-item btn"
                                v-on:click="deleteItem(idx)"
                        >
                            <img class="icon" src="./Images/delete.png">
                        </button>

                    </div>
                </div>
            </div>
        </div>


        <div class="add-task-wrapper">
            <button id="add-task-btn" v-on:click="addItem()">
                + Add a new task
            </button>
        </div>
    
    </div>
</template>
export default {
    data() {
        return {
            taskArr: [],

        }
    },
    methods: {
        addItem() {
            this.taskArr.push({
                name: 'Empty task',
                status: 'Undone'

            })
        },
        deleteItem(idx) {
            this.taskArr.splice(idx, 1)
        },
    }
}

</script>

Upvotes: 0

Views: 681

Answers (1)

John Pavek
John Pavek

Reputation: 2665

I believe this is working, I tossed this up into code sandbox since it uses the same style of .Vue files you're using. I added some numbers to the names which shows it's working as intended. Your checkboxes are not based on any data so they shift weird.

https://codesandbox.io/embed/sweet-ishizaka-s8o71?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 1

Related Questions