vue3+ts 兄弟組件之間傳值的實現
更新時間:2023年11月26日 15:09:11 作者:你的美,讓我癡迷
Vue3是一款流行的前端框架,它支持多種傳值方式,包括兄弟組件之間的傳值,本文主要介紹了vue3+ts 兄弟組件之間傳值的實現,具有一定的參考價值,感興趣的可以了解一下
父級:
<template>
<div>
<!-- <A @on-click="getFlag"></A>
<B :flag="Flag"></B> -->
<A></A>
<B></B>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import A from "./components/A.vue";
import B from "./components/B.vue";
// const Flag = ref(false);
// const getFlag = (params: boolean) => {
// Flag.value = params;
// };
</script>
<style></style>
A組件:
<template>
<div class="A">
<button @click="emitB">派發(fā)一個事件</button>
</div>
</template>
<script setup lang="ts">
// const emit = defineEmits(["on-click"]);
import Bus from '../bus';
let flag = false;
const emitB = () => {
flag = !flag;
// emit("on-click", flag);
Bus.emit('on-click',flag);
};
</script>
<style>
.A{
width: 200px;
height: 200px;
color: #fff;
background: blue;
}
</style>
B組件:
<template>
<div class="B">
<h1>B組件</h1>
{{Flag}}
</div>
</template>
<script setup lang='ts'>
import Bus from "../Bus";
import {ref} from "vue";
let Flag=ref(false);
Bus.on('on-click',(flag:boolean)=>{
Flag.value=flag;
})
// type Props={
// flag:boolean
// }
// defineProps<Props>();
</script>
<style>
.B{
width:200px;
height: 200px;
color:#fff;
background: red;
}
</style>
Bus.ts:
type BusClass = {
emit: (name:string) => void,
on:(name:string,callback:Function)=>void
}
type Pramskey = string | number | symbol;
type List = {
[key:Pramskey]:Array<Function>
}
class Bus implements BusClass{
list: List
constructor() {
this.list={}
}
emit(name: string,...args:Array<any>) {
let evenentName:Array<Function> = this.list[name];
evenentName.forEach(fn => {
fn.apply(this,args)
})
}
on(name:string,callback:Function) {
let fn:Array<Function> = this.list[name] || [];
fn.push(callback);
this.list[name] = fn;
}
}
export default new Bus();
效果圖:

到此這篇關于vue3+ts 兄弟組件之間傳值的實現的文章就介紹到這了,更多相關vue3+ts 兄弟組件傳值內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解讀element-ui使用el-upload,before-upload函數不好使的問題
這篇文章主要介紹了解讀element-ui使用el-upload,before-upload函數不好使的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
vue大文件分片上傳之simple-uploader.js的使用
本文主要介紹了vue大文件分片上傳之simple-uploader.js的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05

