鍍金池/ 問答/HTML/ vue子組件,如何根據(jù)父組件傳進來的id,去查詢詳情,并在子組件中顯示?

vue子組件,如何根據(jù)父組件傳進來的id,去查詢詳情,并在子組件中顯示?

如果我在組件的created方法里面,根據(jù)id去后臺查詢詳情,可以正常顯示,不報錯,但是當父組件id值改變后,并不會再次去后臺查詢了,

,假如我后臺返回的對象時detail,如果寫在computed里面寫
detail: {

    get() {
      let detail
      const gameId = this.id
      querySingleGameDetail(gameId).then(response => {
        detail= response.data.data.detail//我們的結構就是這樣的
      })
      return detail
    }
  }

,頁面就無法正常顯示,
比如在某標簽使用了 {{detail.content}},js就會報錯

Error in render: "TypeError: Cannot read property 'content' of undefined",

所以我現(xiàn)在就是在父組件獲取詳情,直接把詳情傳入給子組件,但是我覺得這么做不優(yōu)雅,所以想咨詢下各位,有沒有更好地解決辦法

回答
編輯回答
冷咖啡

又仔細看了下問題 - -

id改變后應該是發(fā)起了請求,但是因為異步請求還沒返回結果,所以導致了報錯:

Error in render: "TypeError: Cannot read property 'content' of undefined"

建議的解決方案是:

(1)DOM里改為 {{ detail && detail.content}}
或者
(2)computed屬性里增加一個默認值,即:

gameDetail: {
    get() {
      let gameDetail = { content: '' }
      const gameId = this.id
      querySingleGameDetail(gameId).then(response => {
        return response.data.data.singleGameDetail
      })
      return gameDetail
    }
  }
2017年7月3日 03:13
編輯回答
司令

子組件可以這么寫:

props:['id'],
data(){
     return {
       detail: {} ,  
   }  
},
methods: {
    get(id) {
        ...
    }
},
watch: {
    id: 'get'
}

2017年8月24日 16:40
編輯回答
怣痛

我最后的解決辦法是,在data里面再定義一個變量,然后detail的get返回的是這個標量,axios之后的值也是給這個變量賦值

2018年9月21日 10:51