美文网首页
vue父组件和子组件通过sync实现双向数据绑定

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

作者: 小杰的简书 | 来源:发表于2018-11-24 10:46 被阅读0次

父子组件的双向数据绑定

  • 父组件改变数据可以改变子组件, 但是子组件的内容改变并不会影响到父组件
  • 可以通过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>

相关文章

  • Vue sync实现 子组件属性与父组件变量双向绑定

    Vue sync实现 子组件属性与父组件变量双向绑定 父子组件双向绑定语法 父组件可以监听update:title...

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

    父子组件的双向数据绑定 父组件改变数据可以改变子组件, 但是子组件的内容改变并不会影响到父组件 可以通过2.3.0...

  • vue 父子组件通信

    vue设计模式是数据流在组件之间是单向流动,组件内部是数据双向绑定, 父组件一般会通过props绑定数据传递给子组...

  • vue常见面试题

    双向数据绑定的原理: vue父组件向子组件传值(属性绑定):传递数据(props): 传递方法(this.$emi...

  • 面试题总结--vue

    1-vue优点 易学易用、双向数据绑定、组件化、虚拟dom、渐进式 2-组件通讯 父传子:通过属性向子组件...

  • vue组件实现双向绑定

    vue组件实现双向绑定 在封装vue组件过程中,有时候会碰到需要实现组件的某个属性需要和父组件的某个值双向绑定,碰...

  • 【Vue学习笔记】—— 组件之间传递数据 { }

    学习笔记 作者:oMing Vue 组件1.通过绑定传递数据(父组件 ——》 子组件) 2.通过事件传递数据 ...

  • 100字写点东西_Vue_20180001

    最近做项目,写前端,用Vue。双向绑定,父组件向子组件传值,子组件prop,父组件从子组件获取值,$refs,子组...

  • .sync修饰符及MVVM

    .sync修饰符 父组件 子组件 vue的数据响应式

  • iView学习

    父组件向子组件传值 子组件向父组件传值 父组件向子组件传递数据双向绑定问题 注意:声明周期问题 data() 加载...

网友评论

      本文标题:vue父组件和子组件通过sync实现双向数据绑定

      本文链接:https://www.haomeiwen.com/subject/niynwftx.html