父子组件通过sync实现双向数据绑定 - 2018-07-03

  • 2018-07-03 创建

父子双向数据绑定

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

example

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>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.前言 最近在vue 项目中有一个需求, 就是我需要根据不同的类型在页面中放不同的组件, 组件需要跟当前页面的数...
    CHJ_1993阅读 31,743评论 3 12
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 6,725评论 0 6
  • vue概述 在官方文档中,有一句话对Vue的定位说的很明确:Vue.js 的核心是一个允许采用简洁的模板语法来声明...
    li4065阅读 12,118评论 0 25
  • vue.js是什么 是一套构建用户界面的渐进式框架 vue应用组成 一个 Vue 应用由一个通过new Vue创建...
    多多酱_DuoDuo_阅读 4,709评论 0 2
  • property 用于在对象属性赋值或取值时, 需要做一些额外的操作的时候 如果仅仅是赋值,取值,或删除属性,则没...
    橙姜阅读 1,531评论 0 0

友情链接更多精彩内容