父组件向子组件传值
父组件代码如下:
<script setup lang="ts">
import { ref } from "vue";
import AboutView from "./views/AboutView.vue";
const test=ref('测试')
</script>
<template>
<AboutView test="test"></AboutView>
</template>
子组件 AboutView.vue 码如下:
<script setup lang="ts">
interface props {
test:string
}
defineProps<props>()
</script>
<template>
<div>这是父组件传过来的数据:{{test}}</div>
</template>
子组件向父组件传值
父组件代码如下:
<script setup lang="ts">
import { ref } from "vue";
import HomeView from "./views/HomeView.vue";
const test=ref('测试')
const getVal=(val:string)=>{
test.value=val
}
</script>
<template>
<HomeView @_click="getVal"></HomeView>
<div>{{ test }}</div>
</template>
子组件 HomeView.vue 代码如下:
<script setup lang="ts">
const emit=defineEmits(['_click'])
const func=()=>{
emit('_click','我是子组件传过来的数据')
}
</script>
<template>
<button @click="func">按钮</button>
</template>
兄弟组件通信传值
在 Vue3 中,使用 EventBus
(事件总线)是一种常见的跨组件通信方式。EventBus
允许组件通过发送和接收事件来传递数据,而不需要直接相互引用。
如下,创建一个 Bus 事件中心,bus.ts:
interface BusClass{
emit:(funcName:string)=>void
on:(funcName:string,callBack:Function)=>void
}
type Key=number|string|symbol
interface List{
[key:Key]:Array<Function>
}
class Bus implements BusClass{
list:List
constructor(){
this.list={}
}
emit(funcName: string,...args:any[]){
this.list[funcName].forEach((fn)=>{
fn.apply(this,args)
})
}
on(funcName: string, callBack: Function){
const fn=this.list[funcName]||[]
fn.push(callBack)
this.list[funcName]=fn
}
}
export default new Bus()
创建一个子组件 HomeView.vue,如下:
<script setup lang="ts">
import Bus from "../utils/bus";
const func=()=>{
Bus.emit('_click','你好啊')
}
</script>
<template>
<button @click="func">按钮</button>
</template>
创建一个子组件 AboutView.vue,如下:
<script setup lang="ts">
import { ref } from "vue";
import Bus from "../utils/bus";
const test=ref('哈哈哈')
Bus.on('_click',(val:string)=>{
test.value=val
})
</script>
<template>
<div>{{test}}</div>
</template>
创建一个父组件 parent.vue,并将两个子组件引入,如下:
<script setup lang="ts">
import HomeView from "./views/HomeView.vue";
import AboutView from "./views/AboutView.vue";
</script>
<template>
<HomeView></HomeView>
<AboutView></AboutView>
</template>
以上就实现了兄弟之间的组件通信。