码迷,mamicode.com
首页 > 其他好文 > 详细

vue 父子组件数据的双向绑定大法

时间:2019-10-06 18:25:18      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:date   update   事件   pre   nbsp   数据   修饰符   model   ops   

官方文档说明

  • 所有的 prop 都使得其父子 prop 之间形成了一个 单向下行绑定
  • 父级 prop 的更新会向下流动到子组件中,但是反过来则不行
  • 2.3.0+ 新增 .sync 修饰符
  • 以 update:my-prop-name 的模式触发事件实现 上行绑定 最终实现 双向绑定
    举个栗子
    this.$emit(‘update:title‘, newTitle)

代码实现

child.vue

<template>
  <div>
      <input type="text" v-model="sonValue">
      <div>{{ fatherValue }}</div>
  </div>
</template>

<script>

export default {
  props: {
    fatherValue: {
      required: true
    }
  },
  data () {
    return {
      sonValue: this.fatherValue
    }
  },
  watch: {
    sonValue (newValue, oldvalue) {
      this.$emit(update:fatherValue, newValue)
    },
    fatherValue (newValue) {
      this.sonValue = newValue
    }
  }
}
</script>

father.vue

<template>
  <div class="hello">
    <!-- input实时改变value的值, 并且会实时改变child里的内容 -->
    <input type="text" v-model="value">
    <child :fatherValue.sync="value" ></child>
  </div>
</template>
<script>
import Child from ./Child  //引入Child子组件
export default {
  data() {
    return {
      value: ‘‘
    }
  },
  components: {
    child: Child
  }  
}
</script>

 

vue 父子组件数据的双向绑定大法

标签:date   update   事件   pre   nbsp   数据   修饰符   model   ops   

原文地址:https://www.cnblogs.com/YrRoom/p/11627914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!