2017-04-27 49 views
0

我試圖在VueJs組件中的輸入字段的手錶處理函數中設置數據變量。我有這樣的事情:無法訪問手錶處理程序中的數據變量vuejs

data() { 
    return { 
     params: { 
      // default params to 1 month 
      from: new Date().setMonth(new Date().getMonth() - 1), 
      to: Date.now(), 
      skip: 0, 
      limit: 100 
     } 
    } 
} 
watch: { 
    dates: { 
     handler: date => { 
      console.log(this.params) 
      if (date.start) { 
       this.params.from = moment(date.start, "YYYY/MM/DD") 
      } 
      if (date.end) { 
       this.params.to = moment(date.end, "YYYY/MM/DD") 
      } 
     }, 
     deep: true 
    } 
} 

當我設置在視圖模板的dates可變的輸入,我得到一個undefined在控制檯日誌this.params,我得到一個錯誤的嘗試設置this.params.from。所以我試圖用一種方法訪問它:

methods: { 
    printParams() { 
     console.log(this.params) 
    } 
} 

調用它的視圖模板,它正確地解決了params對象。

我在這裏錯過了什麼嗎?

回答

4

,以避免額外的結合,只是避免使用箭頭函數的語法here.Instead去ES6對象速記:

watch: { 
    dates: { 
     handler(date) { 
      console.log(this.params) 
      if (date.start) { 
       this.params.from = moment(date.start, "YYYY/MM/DD") 
      } 
      if (date.end) { 
       this.params.to = moment(date.end, "YYYY/MM/DD") 
      } 
     }, 
     deep: true 
    } 
} 

現在this會綁定爲默認情況下更正上下文。

1

讓我們嘗試bind給你的處理程序

 handler(date) { 
      console.log(this.params) 
      if (date.start) { 
       this.params.from = moment(date.start, "YYYY/MM/DD") 
      } 
      if (date.end) { 
       this.params.to = moment(date.end, "YYYY/MM/DD") 
      } 
     }.bind(this) 
+0

這給了我一個語法錯誤,但我明白了.. –

+0

是啊!我更新:) –