2016-11-24 54 views
0

我與VueJS 2版本的工作,當我點擊裏面的鏈接(比方說)componentA我打電話以componentB是這樣的:等待組件數據加載

<template> 
    <div> 
     hey this is pokemon {{pokemonName}} with ID {{pokemonID}} 
    </div> 
</template> 
<script> 
    export default { 
     data() { 
      return { 
       pokemonName: this.$route.params.name, 
       pokemonID: this.$route.params.pokeid 
      } 
     }, 
     created: function(){ 
      console.log(pokemonID); // here is the error 
      // here I need to do some operations with pokemonID 
     } 
} 
</script> 

後點擊鏈接我正確地看到文本嘿這是pokemon x與ID y但當我檢查控制檯我也讀這個:ReferenceError: pokemonID is not defined

正如你所看到的,我試着用created生命週期掛鉤,因爲我需要在組件加載後立即對pokemonID進行操作。

我該如何解決這個問題?

回答

1

這裏需要使用適當的範圍,你忘了使用this,像以下:

created: function(){ 
    console.log(this.pokemonID); // Now there should be no error 
    // here I need to do some operations with pokemonID 
} 

你所得到的錯誤,因爲在創建函數定義沒有pokemonID變量,雖然有pokemonID變量在組件範圍內,可以通過this.pokemonID訪問。