Vue 的.sync 修饰符的作用

489 阅读1分钟
1. sync修饰符可以实现子组件与父组件的双向绑定,并且可以实现子组件同步修改父组件的值。
2. 父组件通过 props 将值传给子组件,子组件再通过 $emit 将值传给父组件,父组件通过$event获取子组件中的 $emit 传过来的值,如果想要简化这里的代码,可以使用.sync修饰符,实际上就是一个语法糖

App.vue

<template>
  <div class="app">
     {{total}}
    <hr>
    <Child :money.sync="total"/>
    // <Child :money="total" v-on:update:money="total = $event"/>  //两句作用等同
  </div>
</template>

<script>
import Child from "./Child.vue";
export default {
  data() {
    return { total: 10000 };
  },
  components: { Child:Child }
};
</script>

Child.vue

<template>

<div class="child">

    {{money}}

    <button @click="$emit('update:money', money-100)">

        <span>花钱</span>

    </button>

</div>

</template>



<script>

export default {

    props: ["money"]

};

</script>