I have a vue project with a to-do list feature, and I'm facing an issue when trying to use pop()
to remove items from the list. Below is the relevant code snippet:
// components
Vue.component('todoitem', {
template: "<li>Test Item</li>"
})
// app code
var app = new Vue({
el: '#app',
data: {
todos: [
{ text: 'Sample Item 1' },
{ text: 'Sample Item 2' },
{ text: 'Sample Item 3' }
],
button: {
text: 'Hide'
},
seen: true
},
methods: {
addItem: function() {
let item = document.getElementById("list-input").value;
let error = document.getElementById("error");
if (item == "") {
error.style.display = "block";
} else {
app.todos.push({ text: item });
error.style.display = "none";
}
},
removeItem: function() {
this.todos.pop();
},
toggleSeen: function() {
app.seen = !app.seen;
app.button.text = app.seen ? 'Hide' : 'Show';
}
}
});
.todo-list {
list-style-type: square;
}
.todo-list__delete {
display: none;
}
li:hover .todo-list__delete {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
<ul class="todo-list">
<li v-for="todo in todos">
{{ todo.text }}
<a v-on:click="removeItem" class="todo-list__delete" href="#">Delete</a>
</li>
</ul>
<input type="text" id="list-input">
<input type="submit" id="list-submit" v-on:click="addItem">
<span id="error" style="color: red; display: none;">Please Enter Text</span>
<ul>
<todoitem></todoitem>
</ul>
<h2 v-if="seen">SEEN</h2>
<button id="hide-seen" v-on:click="toggleSeen">{{ button.text }}</button>
</div>
When clicking the delete link, the expected behavior is for the corresponding item to be removed. However, I noticed that it actually removes items starting from the bottom instead.
I suspected that using this
inside the removeItem
function might be causing the problem by referencing the delete link rather than the <li>
element itself. So, I attempted both of the following solutions:
removeItem: function() {
this.todos.parentElement.pop();
}
And:
removeItem: function() {
this.parentElement.todos.pop();
}
Unfortunately, neither approach worked as expected.
Can someone explain how this
behaves in Vue.js?