vuejs2-touch-event 上的未定义错误
undefined error on vuejs2-touch-event
我是 Vuejs 2 的新手。我正在尝试使用 phonegap 构建应用程序。最近我正在使用 vue2-touch-event 并尝试处理一些触摸事件。当用户滑动 left/right 时,我将通过事件传递额外的参数。
这是我传递参数的方式
<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
当 returned 回调被调用时 this
没有指向 Vue 实例。这就是您无法访问其中的数据属性并且 undefined
已登录到控制台的原因。
所以 return 一个 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;
}
};
},
}
我是 Vuejs 2 的新手。我正在尝试使用 phonegap 构建应用程序。最近我正在使用 vue2-touch-event 并尝试处理一些触摸事件。当用户滑动 left/right 时,我将通过事件传递额外的参数。
这是我传递参数的方式
<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
当 returned 回调被调用时 this
没有指向 Vue 实例。这就是您无法访问其中的数据属性并且 undefined
已登录到控制台的原因。
所以 return 一个 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;
}
};
},
}