传统的父子组件之间传值,父组件-->子组件 

----父组件(父组件会接收到子组件传回来的方法,并且对数据进行更改)

<template>
  <div class="content">
     <btn :btnName='num' @changeFn= changeFn></btn>
  </div>
</template>

----子组件(用props接,但是子组件只有读的属性,不可以对数据进行更改,所以$emit传回父组件统一更改)

<script>
export default {
  name: 'btn',
  props: {
    btnName:{
        type : [String,Number],
        required: true
    }
  },
  methods: {
      changeNum(){
          this.$emit('changeFn',888)
      }
  },
}
</script>

.sync  相当于上面的父子组件传值简写 父子双向传值语法糖

----父组件(在传入子组件的数据后.sync  不需要在对子组件的$emit进行接收)

<template>
  <div class="content">
     <btn :btnName.sync='num' ></btn>
  </div>
</template>

----子组件($emit传回的不再是函数 而是 update:父组件传过来的变量名称 )

<script>
export default {
  name: 'btn',
  props: {
    btnName:{
        type : [String,Number],
        required: true
    }
  },
  methods: {
      changeNum(){
          this.$emit('update:btnName',888)
      }
  },
}
</script>

总结: 个人认为.sync有点类似于v-model双向绑定,本质上减少了代码量,使代码更加简洁和优化.

Logo

前往低代码交流专区

更多推荐