.sync功能:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中;使用
update:myPropName
模式触发事件,实现双向绑定
//父组件代码
<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>
<style>
</style>
//子组件代码
<template>
<div class="child">
{{money}}
<button @click="$emit('update:money', money-100)">
<span>花钱</span>
</button>
</div>
</template>
<script>
export default {
props: ["money"]
};
</script>
<style>
</style>
在一个包含money prop 的假设的组件中,通过以下方式赋予新值:
$emit('update:money', money-100)
// this.$emit 可以触发事件,并传参
然后父组件可以监听事件并根据需要更新一个本地的数据属性
<Child :money="total" v-on:update:money="total = $event"/>
// $event 可以获取$emit的参数
<Child :money="total" @update:money="total = $event"/>
为了方便起见,这种模式可以缩写,即 .sync 修饰符:
<Child :money.sync="total"/>
网友评论