I have a todo list in vue and I'm using pop() to clear out/delete list items. See the code in question below:
// 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>
The expected behavior is that when delete is clicked, it invokes the removeItem function and with the usage of this in that function it deletes the selected item. However what actually happens is it just deletes nodes starting from the bottom.
I thought the issue is that with this I'm actually referencing the delete link and not actually the <li> element I'm trying to remove. So I tried both:
removeItem: function() {
this.todos.parentElement.pop();
}
And:
removeItem: function() {
this.parentElement.todos.pop();
}
With no luck.
How does this work in Vue?
popfunction actually does. I think you will find the explanation for your behavior. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…push()but that makes sense.