.sync修饰符实际上是一个语法糖。有时候,子组件想要更改一个props属性的值,但是子组件直接修改外部传入的props值会带来维护上的问题,于是可以使用this.$emit('update:propName', newValue)的方式向父组件表达赋新值的意图。
例如下列代码中,子组件想要修改money的值,通过$emit告诉父组件
<template><div class="child">{{money}}<button @click="$emit('update:money', money-100)"><span>花钱</span></button></div></template><script>export default {props: ["money"]};</script><style>.child {border: 3px solid green;}</style>
父组件监听$emit里的update:propName事件,通过$event获取到子组件抛出的值,更新本地的property
<template><div class="app">App.vue 我现在有 {{total}}<hr /><Child :money="total" @update:money="total = $event" /></div></template><script>import Child from "./Child.vue";export default {data() {return { total: 10000 };},components: { Child: Child }};</script><style>.app {border: 3px solid red;padding: 10px;}</style>
为方便起见,Vue为这种模式提供了一个缩写,即.sync修饰符
<Child :money.sync="total" />
