vue父组件和子组件通过sync实现双向数据绑定

2018-11-24  本文已影响0人  小杰的简书

父子组件的双向数据绑定

father.vue

<template>
  <div class="hello">

    //input实时改变wrd的值, 并且会实时改变box里的内容
    <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是父元素传过来的
    <h2>{{ word }}</h2>

  </div>
</template>

<script>
export default {
  name: 'box',
  data() {
    return {
      str: '',
    }
  },
  props: {
    word: ''
  },
  watch: {
    str: function(newValue, oldValue) {
      //每当str的值改变则发送事件update:word , 并且把值传过去
      this.$emit('update:word', newValue)
    }
  }
}
</script>

<style scoped>

</style>

原理

<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) {
      //往父级发射incre事件
      this.$emit('incre', ++this.num)

    }
  },

}
</script>

<style scoped>

</style>
上一篇 下一篇

猜你喜欢

热点阅读