2017-12-25 33 views
1

나는 다음과 같습니다 간단한 뷰 구성 요소가 :Vue watch에서 모델을 사용하는 방법은 무엇입니까?

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(){} 

때문에 화살표 기능 : [(브랜드) =>를 {} ] 자신의 "이"가 없어, 나는 그 문제를 일으키는 것 같아요.

PS :이 코드가 제대로 작동하기 위해서는 어떻게 보일지입니다 :

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

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

을 당신은 또한 일반적으로 뷰 created()mounted() 방법, 심판 Vue.Js Examples - created에 대해 표시 Method Definitions를 사용할 수 있습니다

ECMAScript 2015부터는 개체 초기화 프로그램의 메서드 정의에 대한 짧은 구문이 도입되었습니다.

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

CodePen