vue 父子組件數(shù)據(jù)的雙向綁定大法

官方文檔說明

  • 所有的 prop 都使得其父子 prop 之間形成了一個(gè) 單向下行綁定
  • 父級(jí) prop 的更新會(huì)向下流動(dòng)到子組件中,但是反過來則不行
  • 2.3.0+ 新增 .sync 修飾符
  • update:my-prop-name 的模式觸發(fā)事件實(shí)現(xiàn) 上行綁定 最終實(shí)現(xiàn) 雙向綁定
    舉個(gè)栗子
    this.$emit('update:title', newTitle)

代碼實(shí)現(xiàn)

child.vue

<template>
  <div>
      <input type="text" v-model="sonValue">
      <div>{{ fatherValue }}</div>
  </div>
</template>

<script>

export default {
  props: {
    fatherValue: {
      required: true
    }
  },
  data () {
    return {
      sonValue: this.fatherValue
    }
  },
  watch: {
    sonValue (newValue, oldvalue) {
      this.$emit('update:fatherValue', newValue)
    },
    fatherValue (newValue) {
      this.sonValue = newValue
    }
  }
}
</script>

father.vue

<template>
  <div class="hello">
    <!-- input實(shí)時(shí)改變value的值, 并且會(huì)實(shí)時(shí)改變child里的內(nèi)容 -->
    <input type="text" v-model="value">
    <child :fatherValue.sync="value" ></child>
  </div>
</template>
<script>
import Child from './Child'  //引入Child子組件
export default {
  data() {
    return {
      value: ''
    }
  },
  components: {
    'child': Child
  }  
}
</script>

odk!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容