父子組件通過(guò)sync實(shí)現(xiàn)雙向數(shù)據(jù)綁定 - 2018-07-03

  • 2018-07-03 創(chuàng)建

父子雙向數(shù)據(jù)綁定

  • 父組件改變數(shù)據(jù)可以改變子組件, 但是子組件的內(nèi)容改變并不會(huì)影響到父組
  • 可以通過(guò)2.3.0新增的sync修飾符來(lái)達(dá)到雙向綁定的效果

example

father.vue

 <template>
  <div class="hello">

    //input實(shí)時(shí)改變wrd的值, 并且會(huì)實(shí)時(shí)改變box里的內(nèi)容
    <input type="text" v-model="wrd">

    <box :word.sync="wrd" ></box>

  </div>
</template>

<script>
import box from './box'  //引入box子組件
export default {
  name: 'HelloWorld',
  data() {
    return {
      wrd: ''
    }
  },
  components: {
    box
  }  
}
</script>

<style scoped>

</style>

box.vue

<template>
  <div class="hello">
    <div class="ipt">
      <input type="text" v-model="str">
    </div>

    //word是父元素傳過(guò)來(lái)的
    <h2>{{ word }}</h2>

  </div>
</template>

<script>
export default {
  name: 'box',
  data() {
    return {
      str: '',
    }
  },
  props: {
    word: ''
  },
  watch: {
    str: function(newValue, oldValue) {
      //每當(dāng)str的值改變則發(fā)送事件update:word , 并且把值傳過(guò)去
      this.$emit('update:word', newValue)
    }
  }
}
</script>

<style scoped>

</style>

原理

  • 利用了父級(jí)可以在子元素上監(jiān)聽(tīng)子元素的事件
    father.vue
<template>
  <div class="hello">

    <input type="text" v-model="wrd">

    <box @incre="boxIncremend" ></box>


  </div>
</template>

<script>
import box from './box'
export default {
  name: 'HelloWorld',
  data() {
    return {
      wrd: ''
    }
  },
  methods: {
    boxIncremend(e) {
      this.wrd = this.wrd + e
    }
  },
  components: {
    box
  }
}
</script>

<style scoped>

</style>

box.vue

<template>
  <div class="hello">

      <input type="text" v-model="str">

    <h2>{{ word }}</h2>

  </div>
</template>

<script>
export default {
  name: 'box',
  data() {
    return {
      num: 0
    }
  },
  props: {
    word: ''
  },
  watch: {
    str: function(neww, old) {
      //往父級(jí)發(fā)射incre事件
      this.$emit('incre', ++this.num)

    }
  },

}
</script>

<style scoped>

</style>
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.前言 最近在vue 項(xiàng)目中有一個(gè)需求, 就是我需要根據(jù)不同的類型在頁(yè)面中放不同的組件, 組件需要跟當(dāng)前頁(yè)面的數(shù)...
    CHJ_1993閱讀 31,777評(píng)論 3 12
  • Vue 實(shí)例 屬性和方法 每個(gè) Vue 實(shí)例都會(huì)代理其 data 對(duì)象里所有的屬性:var data = { a:...
    云之外閱讀 2,382評(píng)論 0 6
  • vue概述 在官方文檔中,有一句話對(duì)Vue的定位說(shuō)的很明確:Vue.js 的核心是一個(gè)允許采用簡(jiǎn)潔的模板語(yǔ)法來(lái)聲明...
    li4065閱讀 7,624評(píng)論 0 25
  • vue.js是什么 是一套構(gòu)建用戶界面的漸進(jìn)式框架 vue應(yīng)用組成 一個(gè) Vue 應(yīng)用由一個(gè)通過(guò)new Vue創(chuàng)建...
    多多醬_DuoDuo_閱讀 1,138評(píng)論 0 2
  • property 用于在對(duì)象屬性賦值或取值時(shí), 需要做一些額外的操作的時(shí)候 如果僅僅是賦值,取值,或刪除屬性,則沒(méi)...
    橙姜閱讀 227評(píng)論 0 0

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