2017-12-17 7 views
0

私はVuejs 2の新機能です。私はphonegapを使用してアプリケーションを構築しようとしています。最近私はvue2 - タッチイベントを使用して、いくつかのタッチイベントを処理しようとしています。ユーザーが左右にスワイプすると、イベントで余分なパラメータが渡されます。ここでvuejs2-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; 
      } 
     }; 
    }, 
} 

ある問題は、私は(this.todoLists)はconsole.logに未定義取得しています。誰も私がこの問題を解決するのを助けることができますか? TIA

+0

多分リターン関数を使用しないでください。通常の関数を使用し、同じロジックを使用するだけです。 – samayo

+0

@samayo vuejs2-touch-eventハンドラ関数にパラメータを渡す場合は、return関数を使用する必要があります。どちらかは、イベントを聞いていないでしょう。 –

答えて

0

返されたコールバックが呼び出されると、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インスタンス変数に向けて指し示す変数を宣言することで closureを利用することができるように arrow 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; 
      } 
     }; 
    }, 
} 
+0

。どのように私はこれを逃したのですか?それは魅力のように動作します –

+0

ありがとう@Vamsiクリシュナ..私は前にこの方法を試した、多分別のエラーのために働かなかった。ご回答いただきありがとうございます。 –