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

父子组件的双向数据绑定

  • 父组件改变数据可以改变子组件, 但是子组件的内容改变并不会影响到父组件
  • 可以通过2.3.0新增的sync修饰符来达到双向绑定的效果

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>

原理

  • 利用了父级可以在子元素上监听子元素的事件
    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) {
      //往父级发射incre事件
      this.$emit('incre', ++this.num)

    }
  },

}
</script>

<style scoped>

</style>
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值