Vue中有如下规则:
- 组件不能修改props外部数据
- $emit可以触发事件并传参
- $event可以获取$emit的参数
基于上述规则来看一个示例:
// father.vue组件
<template>
<div class="app">
App.vue 我现在有 {{total}}
<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)">花钱</button>
</div>
</template>
<script>
export default {
props: ["money"]
};
</script>
- 如果child.vue组件自身修改外部数据'money',Vue会报错
<button @click="money -= 100">花钱</button>
- 因此要通过$emit发布事件'update:money',并传入参数'money-100'
<button @click="$emit('update:money', money-100)">花钱</button>
- father.vue组件监听'update:money'事件,并通过$event接受参数
<Child :money="total" v-on:update:money="total = $event"/>
- 以此实现了两个组件的通信,修改了外部数据
- 由于这种场景很常见,Vue引入了.sync修饰符
<Child :money.sync="total"/>
//等价于
<Child :money="total" v-on:update:money="total = $event"/>