浅析 Vue 中的 .sync 修饰符
把学到知识快速转化为博客,然后忘掉它吧 ——怕猫的程序员
Vue
中的 .sync
修饰符,是一个重要的语法糖,它可以快速实现组件间的通信
当我们需要做的只是让子组件改变父组件状态时,代码更容易区分
它会被扩展为一个自动更新父组件属性的v-on
监听器
下面看一个例子,例子中,子组件(Child
)通过 $emit
去修改父组件(App
)的 total
,
如果不适用 .sync
,就需要在 父组件中完整的写出
<Child :money="total" v-on:update:money="total = $event"/>
如果使用语法糖
<Child :money.sync="total"/>
源码请点击
// App.vue
<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>