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

2018-06-11  本文已影响47人  IT散人

官方文档说明

代码实现

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>

odk!

上一篇 下一篇

猜你喜欢

热点阅读