鍍金池/ 問答/HTML/ 我要在父組件的computed中使用子組件的值,有什么辦法嗎?或者父組件使用子組

我要在父組件的computed中使用子組件的值,有什么辦法嗎?或者父組件使用子組件的computed的值

我要在父組件的computed中使用子組件的值,有什么辦法嗎?

computed: {

  addButtonDisabled() {
    return this.$refs.queryBox.selectSportsType === _const.ALL_SELECTION
  },
  
  報錯,Error in render: "TypeError: Cannot read property 'selectSportsType' of undefined"

百度了下

computed: {
  addButtonDisabled() {
    this.$nextTick(()=>{
      return this.$refs.queryBox.selectSportsType === _const.ALL_SELECTION
    })
  },
    

這樣才可以獲取到

可是這樣又沒辦法用computed了,
請問有什么解決辦法嗎,謝謝

目前的寫法,父組件聲明要用的值addButtonDisabled傳給子組件,子組件內(nèi)修改,下部分為子組件代碼

computed: {
  addButtonDisabledProp(){
    return this.selectSportsType === _const.ALL_SELECTION || this.selectParticipantType === _const.ALL_SELECTION
  }
},
watch:{
  addButtonDisabledProp(){
    this.$emit('update:addButtonDisabled', this.addButtonDisabledProp)
  }
},
回答
編輯回答
老梗

在父組件的 data中聲明你需要用到的值來存儲子組件的那個值;
因為組件掛載順序的問題 父組件data聲明的時候子組件的data還沒有初始化好;
所以你要在父組件mounted中通過this.$refs.xxxx.xxxx拿到這個值,并賦值給data中的值;
父級的computed 會根據(jù)這個data中的值重新計算

2018年3月2日 04:42
編輯回答
純妹

子組件的值emit出事件修改父組件的data,然后根據(jù)需求執(zhí)行computed,推薦watch父組件的data

2018年6月12日 02:25