19、vue3组件通信
1、props
常见搭配形式
概述:props
是使用频率最高的一种通信方式,常用与 :父 ↔ 子。
- 若 父传子:属性值是非函数。
- 若 子传父:属性值是函数。
Father.vue
<template><div><h1>父亲</h1><h1>父亲有遗产:【{{ moeny }}】元,要传给儿子</h1><h3>父亲收到儿子送的手机:{{ erziPhone }}</h3><h1>--------------------------</h1><Son :father="moeny" :getIphone="getIphone"/></div>
</template><script setup lang="ts" name="Father">
import Son from './Son.vue';
import { ref } from 'vue';
let moeny=ref(1000)
let erziPhone=ref()function getIphone(value:string){erziPhone.value=value}</script><style scoped></style>
Son.vue
<template><div><h1>儿子</h1><h1>儿子要送父亲一部【{{ iphone }}】手机</h1><h3>继承父亲的遗产:{{ father }}</h3><button @click="getIphone(iphone)">送给父亲手机</button></div>
</template><script setup lang="ts" name="Son">
import { ref } from 'vue';
let iphone=ref('苹果')defineProps(['father','getIphone'])
</script><style scoped></style>
2、自定义事件
-
概述:自定义事件常用于:子 => 父。
-
注意区分好:原生事件、自定义事件。
-
原生事件:
- 事件名是特定的(
click
、mosueenter
等等) - 事件对象
$event
: 是包含事件相关信息的对象(pageX
、pageY
、target
、keyCode
)
- 事件名是特定的(
-
自定义事件:
- 事件名是任意名称
- 事件对象
$event
: 是调用emit
时所提供的数据,可以是任意类型!!!
Father.vue
<template><div><h1>父亲</h1><h1>父亲有遗产:【{{ moeny }}】元,要传给儿子</h1><h3>父亲收到儿子送的手机:{{ erziPhone }}</h3><h1>--------------------------</h1><!-- 给子组件绑定自定义事件 --><Son :father="moeny" @get-iphone="Iphone"/></div>
</template><script setup lang="ts" name="Father">
import Son from './Son.vue';
import { ref } from 'vue';
let moeny=ref(1000)
let erziPhone=ref('')function Iphone(value:string){console.log('value',value)erziPhone.value=value}</script><style scoped></style>
Son.vue
<template><div><h1>儿子</h1><h1>儿子要送父亲一部【{{ iphone }}】手机</h1><h3>继承父亲的遗产:{{ father }}</h3><button @click="emit('get-iphone',iphone)">送给父亲手机</button></div>
</template><script setup lang="ts" name="Son">
import { ref } from 'vue';
let iphone=ref('苹果')defineProps(['father'])
// 声明事件
const emit=defineEmits(['get-iphone'])
</script><style scoped></style>
3、mitt
mitt可以实现任意组件间通信
mitter.ts
import mitt from "mitt";const emitter=mitt()export default emitter
Son.vue
<template><div><h1>儿子</h1><h1>儿子要送父亲一部【{{ iphone }}】手机</h1><button @click="songIphone">送给父亲手机</button></div>
</template><script setup lang="ts" name="Son">
import { ref } from 'vue';
import emitter from '@/utils/mitter';
let iphone=ref('苹果')function songIphone(){emitter.emit('faIphone',iphone)}
</script><style scoped></style>
Father.vue
<template><div><h1>父亲</h1><h3>父亲收到儿子送的手机:{{ erziPhone }}</h3><h1>--------------------------</h1><!-- 给子组件绑定自定义事件 --><Son/></div>
</template><script setup lang="ts" name="Father">
import emitter from '@/utils/mitter';
import { onUnmounted } from 'vue';
import Son from './Son.vue';
import { ref } from 'vue';let erziPhone=ref('')emitter.on('faIphone',(value:any)=>{erziPhone.value=value
})onUnmounted(()=>{// 解绑事件emitter.off('faIphone')
})</script><style scoped></style>
4、v-model
双向绑定,实现 父↔子 之间相互通信。这种方式用的少。