vue兄弟组件传参
一、eventBus
创建一个JS文件 eventBus.js
import Vue from 'vue' const eventBus = new Vue() export default eventBus
使用时 在 要使用的组件中 import 引入 eventBus.js
使用 $emit 传递自定义方法和参数 就和 子组件传父组件一样
如下 传了一个自定义方法 addItem 和参数 inputValue
eventBus.$emit('addItem', this.inputValue)
在要接收的兄弟组件中同样引入 eventBus.js
触发自定义方法 addItem 同时触发自身的方法 handleEvent
eventBus.$on('addItem', this.handleEvent)
handleEvent 中的参数即是之前 传递的参数 inputValue
handleEvent (value) { console.log(value)... // value即是传递的inputValue }
二、mitt插件
yarn add mitt
或者
npm install mitt
方式一: 在main.js中注册挂载到全局
import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' // 导入mitt import mitt from 'mitt' const app = createApp(App) // vue3挂载到全局 app.config.globalProperties.$mitt = new mitt(); app.use(createPinia()).mount('#app')
2.在组建中使用
组件1 发送数据
<template> <h2>组件1: {{money}}</h2> <button @click="sendMitt">$mitt发送数据</button> </template> <script> import { getCurrentInstance, ref } from 'vue' export default { setup() { let { proxy } = getCurrentInstance() let money = ref(100) function sendMitt() { proxy.$mitt.emit('mittFn', money.value-=2) } return { money, sendMitt, } } } </script>
组件2 接收数据
<template> <h2>组件2接收mitt发送的数据: {{money}}</h2> </template> <script> import { getCurrentInstance, ref } from 'vue' export default { setup() { let { proxy } = getCurrentInstance() let money = ref('') proxy.$mitt.on('mittFn', (res) => { console.log(res) money.value = res }) return { money, } } } </script>
方式二: 创建mitt.js文件
import mitt from 'mitt' export default new mitt()
组件1 发送数据
<template> <h2>组件1: {{money}}</h2> <button @click="sendMitt">$mitt发送数据</button> </template> <script> import { ref } from 'vue' import mitt from '../mitt/index.js' export default { setup() { let money = ref(100) function sendMitt() { mitt.emit('mittFn', money.value-=2) } return { money, sendMitt, } } } </script>
组件2 接收数据
<template> <h2>组件2接收mitt发送的数据: {{money}}</h2> </template> <script> import { ref } from 'vue' import mitt from '../mitt/index.js' export default { setup() { let money = ref('') mitt.on('mittFn', (res) => { console.log(res) money.value = res }) return { money, } } } </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」