应用场景:组件获取 props 外部数据后,需要修改数据。
Vue 规定:
组件不能修改 props 外部数据;
$emit 可以触发事件,并且传参;
$event 可以获取 $emit 的参数。
示例:
<template>
<div class="app">
App.vue 我现在有 {{total}}
<hr>
<Child :money.sync="total"/>
</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>
<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>
点击 花钱
总结:
:money.sync = "total" 等价于 :money = "total" v-on:update:money = "total = $event",.sync修饰符就是一个语法糖。






网友评论