我是Vuejs 2的新手。我正在尝试使用phonegap构建应用。最近我正在使用vue2-touch-event并试图处理一些触摸事件。当用户向左/向右滑动时,我正在通过事件传递额外的参数。
以下是我如何传递参数
<label v-touch:swipe.right="doneLisItem(index)">
</label>
这是我在脚本中的代码
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;
}
};
},
}
问题是我在console.log(this.todoLists)中未定义。任何人都可以帮我解决这个问题。 TIA
答案 0 :(得分:0)
调用返回的回调时this
未指向Vue实例。这就是您无法访问数据属性的原因,并在控制台中记录了undefined
。
所以返回一个arrow function,以便this
以词法方式绑定并指向vue实例
doneLisItem(index) {
return (direction, event) => {
console.log(index);
console.log(this.todoLists);
if (!this.todoLists[index].completed) {
this.todoLists[index].completed = true;
}
};
},
或者你可以通过声明一个指向函数内正确的vue实例变量的变量来使用closure
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;
}
};
},
}