Vue 中的.sync 修饰符的功能是 : 当一个子组件改变了一个 props 的值时,这个变化也会同步到父组件中所绑定。
Vue规则:
- 组件不能修改props外部数据
this.$emit可以触发事件,并传参$event可以获取$emit的参数 下面我们通过一个实例来说明这是如何运用的。
- 场景描述
爸爸给儿子打钱,儿子要花钱怎么办?
答 : 儿子打电话(触发事件)向爸爸要钱
示例 :
App.vue
<template>
<div class="app">
App.vue 我现在有 {{total}}
<hr>
<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>
效果展示:点击花钱数字会减少100
由于这样的场景很常见,所以尤雨溪发明了.sync修饰符。
:money.sync="total"
等价于
:money="total" v-on:update:money="total=$event"
- 代码
<Child :money.sync ="total"/>会被扩展成<Child :money="total" v-on:update:money="total = $event"/>,就是一个语法糖。