vue 父子组建双向通信 .sync 修饰符

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

demo

<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>


<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>

原理

<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>
<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>


猜你喜欢

转载自blog.csdn.net/weixin_40222803/article/details/80925837
今日推荐