vue3+ts 兄弟组件之间传值的实现
作者:你的美,让我痴迷
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">派发一个事件</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 兄弟组件传值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!