vuejs2-touch-event上的未定义错误

问题描述 投票:0回答:1

我是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

cordova vuejs2 phonegap
1个回答
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;
            }
        };
    },
} 
© www.soinside.com 2019 - 2024. All rights reserved.