vue3+ts 兄弟組件之間傳值的實現(xiàn)
更新時間:2023年11月26日 15:09:11 作者:你的美,讓我癡迷
Vue3是一款流行的前端框架,它支持多種傳值方式,包括兄弟組件之間的傳值,本文主要介紹了vue3+ts 兄弟組件之間傳值的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
父級:
<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();
效果圖:
到此這篇關(guān)于vue3+ts 兄弟組件之間傳值的實現(xiàn)的文章就介紹到這了,更多相關(guān)vue3+ts 兄弟組件傳值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue2父組件傳遞props異步數(shù)據(jù)到子組件的問題
本篇文章主要介紹了vue2父組件傳遞props異步數(shù)據(jù)到子組件的問題,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06關(guān)于Vue3中defineProps用法圖文詳解
在vue3中組件傳參有很多種方式,和v2大差不差,但是有的地方還是有很多的區(qū)別,下面這篇文章主要給大家介紹了關(guān)于Vue3中defineProps用法的相關(guān)資料,需要的朋友可以參考下2022-11-11解讀element-ui使用el-upload,before-upload函數(shù)不好使的問題
這篇文章主要介紹了解讀element-ui使用el-upload,before-upload函數(shù)不好使的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03使用vue實現(xiàn)滑動滾動條來加載數(shù)據(jù)
在vuejs中,我們經(jīng)常使用axios來請求數(shù)據(jù),但是有時候,我們請求的數(shù)據(jù)量很大,那么我們?nèi)绾螌崿F(xiàn)滑動滾動條來加載數(shù)據(jù)呢,接下來小編就給大家介紹一下在vuejs中如何實現(xiàn)滑動滾動條來動態(tài)加載數(shù)據(jù),需要的朋友可以參考下2023-10-10vue大文件分片上傳之simple-uploader.js的使用
本文主要介紹了vue大文件分片上傳之simple-uploader.js的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05