2017-12-25 30 views
1

私はこのようになりますシンプルなVueの成分を有する:Vueウォッチでモデルを使用するには?

export default { 
    data: function() { 
     return { 
      brands: [], 
      models: [ 
       {id:1, name: 'one'}, 
       {id:2, name: 'two'}, 
       {id:3, name: 'tree'} 
      ], 

      filters: {}, 

      filter: { 
       brand: null, 
       model: null, 
       price: null, 
       year: null 
      } 
     } 
    }, 
    watch: { 
     'filter.brand': (brand) => { 
      console.log('filter.brand', this, this.models) 

      socket.emit('brands.models.get', brand, (models) => { 
       console.log(models) 

       console.log(this.models) 

       this.models = models; 

       console.log(this.models) 
      }) 
     }, 
    } 
} 

主な問題は、私はソケットからデータを受信したとき、私はモデルを見る傾けることです。

たとえば、console.log(this.models)は未定義を返します。以下のように見えますフルここ

何を印刷:

enter image description here

答えて

1

あなたはウォッチャーのための通常の機能を使用してみてください。

'filter.brand': function(){} 

矢印の機能なので:[(ブランド)=> {} ]自分自身の "this"を持っていない、私はそれが問題を引き起こしていると推測している。

PS:これはあなたのコードが正しく動作するためにはどのように見えるかです:

'filter.brand': function(brand){ 
     //Access to the vue instance 
     var me = this; 

     socket.emit('brands.models.get', brand, (models) => { 
      me.models = models; 
     }) 
    }, 
0

ます。またMethod Definitionsを使用することができ、一般的Vueのcreated()mounted()方法、REF Vue.Js Examples - created

のために示しました

ECMAScript 2015以降、オブジェクト初期化子のメソッド定義の構文が簡略化されています。

created() { 
    this.filter.brand = 'f' 
    }, 
    watch: { 
    'filter.brand'(brand) { 
     console.log('filter.brand', this, this.models) 
    }, 
    } 

例、CodePen

関連する問題