I'm new in Vuejs 2. I'm trying to build a app using phonegap. Recently i'm using vue2-touch-event and trying to handle some touch event. When user swipe left/right i'm passing extra parameter with the event.
Here is how i passed the parameter
<label v-touch:swipe.right="doneLisItem(index)">
</label>
Here is my code in the script
data() {
return {
newList: '',
todoLists: [],
};
},
methods: {
doneLisItem(index) {
return function(direction, event) {
console.log(index);
console.log(this.todoLists);
if (!this.todoLists[index].completed) {
this.todoLists[index].completed = true;
}
};
},
}
The problem is i'm getting undefined in console.log(this.todoLists). Can anyone help me to solve this problem. TIA
When the returned callback is invoked this
does not point to the Vue instance . That's the reason you cannot access the data properties in and undefined
is logged in the console.
So return an arrow function so that that this
is bound lexically and points towards the vue instance
doneLisItem(index) {
return (direction, event) => {
console.log(index);
console.log(this.todoLists);
if (!this.todoLists[index].completed) {
this.todoLists[index].completed = true;
}
};
},
Or you can make use of closure by declaring a variable pointing towards the correct vue instance variable inside the function
methods: {
doneLisItem(index) {
var vm = this; //now the Return function has a closure over vm which is the correct vue instance
return function(direction, event) {
console.log(index);
console.log(vm.todoLists);
if (vm.todoLists[index].completed) {
vm.todoLists[index].completed = true;
}
};
},
}