【Vue3】兄弟组件传参

1. 借助父组件传参

A 组件派发一个事件,修改 flag 的值,先传递给父组件,然后由父组件传递给 B 组件。

缺点:必须由 App.vue 处理中间逻辑。

A.vue

<template>
  <div class="A">
    <h1>A组件h1>
    <button @click="emitB">派发一个事件button>
  div>
template>

<script setup lang="ts">
const emit = defineEmits(['on-click'])
let flag = false
const emitB = () => {
  flag = !flag
  emit('on-click', flag)
}
script>

<style scoped>
.A {
  width: 200px;
  height: 200px;
  color: #fff;
  background: blue;
}
style>

App.vue

<template>
  <div>
    <A @on-click="getFlag">A>
    <B :flag="Flag">B>
  div>
template>

<script setup lang="ts">
import A from './components/A.vue';
import B from './components/B.vue';
import { ref } from 'vue'
let Flag = ref<boolean>(false)
const getFlag = (flag:boolean) => {
  Flag.value = flag
}
script>

<style scoped>

style>

B.vue

<template>
  <div class="B">
    <h1>B组件h1>
    {{ flag }}

  div>
template>

<script setup lang="ts">
type Props = {
  flag: boolean
}
defineProps<Props>()

script>

<style lang="scss" scoped>
.B{
  width: 200px;
  height: 200px;
  color: #fff;
  background: red;
}
style>

【Vue3】兄弟组件传参_第1张图片

2. Event Bus

Event Bus(事件总线)是一种在Vue中实现组件间通信的模式。它使用了Vue实例作为中央的事件中心,允许任何组件注册监听器并触发事件。通过事件总线,兄弟组件之间可以进行解耦合的通信。

原理是利用了 JavaScript 设计模式的发布-订阅(Publish-Subscribe Pattern),然后由事件调度中心(Event Loop)进行处理。

// 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>): void {
    let eventName: Array<Function> = this.list[name]
    eventName.forEach(fn =>{
      fn.apply(this, args)
    })
  }
  on(name: string, callback: Function): void {
    let fn:Array<Function> = this.list[name] || []
    fn.push(callback)
    this.list[name] = fn
  }
}
export default new Bus()

<template>
  <div>
    <h1>A组件h1>
    <button @click="emitB">派发一个事件button>
    <hr>
  div>
template>

<script setup lang="ts">
import Bus from '../Bus'
let flag = false
const emitB = () =>{
  flag = !flag
  Bus.emit('on-click', flag)
}
script>

<style scoped>style>

<template>
  <div>
    <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
})

script>

<style scoped>style>

<template>
  <div>
    <A>A>
    <B>B>
  div>
template>

<script setup lang="ts">
import A from './components/A.vue'
import B from './components/B.vue'

script>

<style scoped>style>

【Vue3】兄弟组件传参_第2张图片

你可能感兴趣的:(Vue,vue.js,javascript,ecmascript)