组件是 vue.js最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互进行直接的引用,所以组件间的相互通信是非常重要的。
1. props / $emit
![](https://img-blog.csdnimg.cn/b3b5fa45a5644a108b7e91810a291419.png)
常用场景: 父子传参
父组件
<template>
<div class="box">
<h1>组件间通信: props</h1>
<h3>父组件</h3>
<div>{{count}}</div>
<button @click="count++">修改父组件的值</button>
<Child :count="count" :changeCount="changeCount"></Child>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import Child from './Child.vue'
const count = ref(0)
// 修改父组件的值
const changeCount = (num=1)=>{
count.value+=num
}
</script>
子组件
<template>
<div class="box">
<h3>Child</h3>
<div>父组件传过来的参数:{{count}}</div>
<button @click="changeCount(3)">修改父组件的值</button>
</div>
</template>
<script lang="ts" setup>
// 接收父组件传过来的参数
defineProps<{
count:number
changeCount:(num : number)=>void
}>()
</script>
自定义事件emit
常用场景: 子给父传参
父组件
<template>
<div class="box">
<h1>组件间通信: custom_event</h1>
<!-- 绑定系统内置click -->
<!-- 元素绑click 系统事件,系统触发,可以拿到事件对象 -->
<button @click="clickHandler">按钮1</button>
<!-- 组件绑定系统事件,会自动绑定到子组件的根标签上 d当子组件没有根标签会被当成自定义事件 -->
<Event1 @click="compClickHandler"></Event1>
<!-- 自定义事件 -->
<!-- 组件绑xxx 自定义事件,在子组件中使用emit接收-->
<Event1 @xxx="xxxHandler" @yyy="yyyHandler"></Event1>
<!--
组件绑定 系统内置事件 跟vue2刚好相反 vue2需要使用.native ,vue3默认就是
组件绑定自定义事件,是语法上的差异
-->
</div>
</template>
<script lang="ts" setup>
import Event1 from "./Event1.vue";
const clickHandler = (e: Event) => {
console.log('点击了按钮', e)
}
const compClickHandler = (e: Event) => {
console.log('组件点击事件', e.target);
console.log('组件点击事件', e);
}
const xxxHandler = () => {
console.log('触发了xxx事件');
}
const yyyHandler = (e: string) => {
console.log('触发了yyy事件', e);
}
</script>
子组件
<template>
<div class="box">
<h3>Event1组件</h3>
<h4>子组件内容</h4>
<button @click="emit('xxx')">触发xxx事件</button>
<button @click="emit('yyy', '我爱你')">触发yyy事件</button>
</div>
</template>
<script lang="ts" setup>
const emit = defineEmits(['xxx', 'yyy'])
</script>