鍍金池/ 問答/HTML5  HTML/ vue子組件修改父組件的值

vue子組件修改父組件的值

圖片描述

括號里的是子組件,我點(diǎn)擊按鈕為true傳到父組件需要改變他的狀態(tài),但是報(bào)錯說:避免直接更改一個(gè)PROP,因?yàn)槊慨?dāng)父組件重新呈現(xiàn)時(shí),該值就會被覆蓋。

子組件

export default{
  props: {
      onlyContent: {
        type: Boolean,
        default: false
      }
  },
  methods: {
      toggleContent (event) {
        if (!event._constructed) {
            return
        }
        this.onlyContent = !this.onlyContent
        this.$emit('contentToggle', this.onlyContent)
      }
  }
}
父組件

<v-ratingSelect v-on:contentToggle="contToggle" :only-content="onlyContent"></v-ratingSelect>

data () {
  return {
    onlyContent: false
  }
}

contToggle (event) {
  this.onlyContent = event
}
回答
編輯回答
淺時(shí)光

this.onlyContent = !this.onlyContent,錯誤,在子組件里面不能直接修改prop值;
如果要對某個(gè)prop 進(jìn)行雙向綁定,可以使用.sync 修飾符;看下文檔就懂了;sync

2018年1月27日 05:21
編輯回答
胭脂淚

在父組件中修改onlyContent

// 子組件
toggleContent (event) {
    ...
    this.$emit('contentToggle')
}

// 父組件
contToggle () {
  this.onlyContent = !this.onlyContent
}
2018年5月13日 03:02