我是 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)中未定义。谁能帮我解决这个问题。蒂亚
当返回的回调被调用时this
不指向 Vue 实例。这就是您无法访问 中的数据属性的原因,并且undefined
记录在控制台中。
所以返回一个箭头函数,以便该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 实例变量的变量来利用闭包
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;
}
};
},
}