Vue 修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。 当我们需要做的只是让子组件改变父组件状态时,代码更容易区分 它并将其扩展为一个自动更新父组件属性的 v-on 监听器。
<template>
<div class="app">
App.vue 我现在有 {{total}}
<hr>
<!-- 不使用 .sync -->
<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>