vue.sync 修饰符
vue.sync 作用:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中。
它会被扩展为一个自动更新父组件属性的 v-on 监听器。
例子:
//父组件
<template>
<div class="app">
App.vue 我现在有 {{total}}
<hr>
//给子组件 props 传值,使用 .sync 修饰符
<Child :money.sync="total"/>
</div>
</template>
<script>
//引入子组件
import Child from "./Child.vue";
export default {
data() {
return { total: 10000 };
},
components: { Child: Child }
};
</script>
//子组件
<template>
<div class="child">
{{money}}
//当子组件需要更新 money 的值时,需要触发一个更新事件
<button @click="$emit('update:money', money-100)">
<span>花钱</span>
</button>
</div>
</template>
<script>
export default {
// 引用父组件数据
props: ["money"]
};
</script>
上面代码中,在点击 button 后,子组件会触发一个更新事件,并将 money -100:
<button @click="$emit('update:money', money-100)">
<span>花钱</span>
</button>
父组件用到 .sync 修饰符会监听 update:money 事件并更新数据:
<Child :money.sync="total"/>
会被扩展为:
//$event 会获取到 $emit 的参数
<Child :money="total" v-on:update:money="total = $event"/>