Vue 中的 .sync 修饰符

234 阅读1分钟

代码示例

父组件App.vue

<Child :money.sync="total"/>
    //等价于<Child :money="total" v-on:update:money = "total = $event"/>

子组件Child.vue

<template>
  <div class="child">
    {{money}}
    <button @click="$emit('update:money', money-100)">
    </button>
  </div>
</template>

<script>
export default {
  props: ["money"]
};
</script>

简述Vue 中 .sync 修饰符的作用

1、父组件传给子组件一个变量money并用"v-on" 监听

2、子组件this.$emit触发事件,并传参数money-100,父组件通过$event获取$emit的参数

3、新的参数money-100传给父组件的total

4、新的total值再次传给变量money

vue 修饰符.sync的功能是:将上述步骤的代码

<Child :money="total" v-on:update:money = "total = $event"/>

简化,缩写为

<Child :money.sync="total"/>