vue 父子組件數據的雙向綁定大法


官方文檔說明

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

代碼實現

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實時改變value的值, 並且會實時改變child里的內容 -->
    <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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM