用法
vue 的子组件不能直接使用父组件的数据,需要用到 props 传递数据。vue 通过自定义事件系统来帮助我们修改父组件上的数据。 子组件通过 $emit() 方法修改父组件上面的数据。
在 Vue 中,当我们想通过子组件来修改父组件中的值时,通常的写法是
父组件
<template>
<div class="app">
我有 {{total}}
<hr>
<Child :number="total" v-on:update:number="total=$event"/> //在父组件的子组件器上使用v-on监听这个自定义事件
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
data() {
return { total: 100000 };
},
components: { Child: Child }
};
</script>
<style>
.app {
border: 3px solid red;
padding: 10px;
}
</style>
<hr/>
// 子组件
<template>
<div>
{{number}}
<button @click="$emit('update:number',number-=100)">整活-100</button>
</div>
</template>
<script>
export default {
props:['number'] //在子组件上触发一个自定义事件,并传递一个自定义事件
}
</script>
<style scoped>
</style>
- 子组件的自定义事件通过
$emit通知父组件,而父组件通过v-on监听子组件的自定义事件 - 子组件是无法直接改变父组件的数据的,只能通过父组件自己改变自己数据,数据变化的操作一定是放在父组件上面
.sync
<Child :number="total" v-on:update:number="total=$event"/>
在父组件监听子组件的时候,每次都会写很长的代码,这时候 .sync 修饰符便解决了这个问题
<Child :number.sync="total"></Child>
.sync 相当于一个语法糖,可以让开发者不用写此冗长的代码.
- Vue 规则:组件不能修改 props 外部数据.
- Vue 规则:$emit 可以触发事件,并传参.
- Vue 规则:emit 的参数
学了吗今天