I have v-for looping and elements inside it have :click calling a function. That function is being triggered automatically on every single element on page load!
<li v-if="itemSaved.length > 0" v-for="(item, index) in items" class="list-group-item">
<div class="pull-right m-l">
<i v-if="itemSaved[index] == 'not saved'" class="icon-plus" :click="addItem(item.id)"></i>
<i v-else class="icon-check" :click="removeItem(item.id)"></i>
</div>
</li>
export default {
data: () => ({
itemSaved: [{"id":1, "name":"Jim"},{"id":2, "name":"Max"}]
}),
methods: {
addItem: function(id){
console.log('add item ' + id)
},
removeItem: function(id){
console.log('remove item ' + id)
}
}
}
Basically I get a list of add item 1
and add item 2
in the console log
Should be:
@click="removeItem(item.id)"
Not:
:click="removeItem(item.id)"
When you have :click="removeItem(item.id)"
you are actually binding the result of the removeItem(item.id)
method call to the click
property. Which is why the method executes "automatically".
@click="handler"
is a shorthand to v-on:click="handler"
- the event handling directive.
:click="handler"
is a shorthand to v-bind:click="handler"
, the property binding directive.