当前位置: 首页 > article >正文

vue3 setup模式使用事件总线Event bus用mitt,app.config.globalProperties.$bus

环境介绍package.json中的内容如下 需要 npm install mitt:

{
  "name": "event_bus_test",
  "version": "0.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "mitt": "^3.0.1",
    "pinia": "^2.2.6",
    "vue": "^3.5.13",
    "vue-router": "^4.4.5"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.2.1",
    "vite": "^6.0.1",
    "vite-plugin-vue-devtools": "^7.6.5"
  }
}

通过npm create vue@latest创建一个名为event_bus_test的项目项,目目录结构如下:

在这里插入图片描述

main.js中的内容如下:

import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
// 导入
import mitt from 'mitt';
const emitter =mitt();


const app = createApp(App) 
// 注册全局bus总线对象
app.config.globalProperties.$bus =  emitter
app.use(createPinia())
app.use(router)

app.mount('#app')

App.vue中的内容如下:

<script setup>
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
import {getCurrentInstance} from 'vue';
const { proxy } = getCurrentInstance()

const change_title = ()=>{
  // 通过点击事件来触发监听对象 proxy.$bus.on("test") 这个函数 所以这第一个参数要一模一样
  proxy.$bus.emit("test", "大标题")
}
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />

      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink to="/about">About</RouterLink>
      </nav>
      <button @click="change_title">点击远程修改文档标题</button>
    </div>
  </header>

  <RouterView />
</template>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

nav a {
  display: inline-block;
  padding: 0 1rem;
  border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
  border: 0;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;

    padding: 1rem 0;
    margin-top: 1rem;
  }
}
</style>

HomeView.vue中的内容如下:

<template>
  <main>
    <TheWelcome :title=title />
  </main>
</template>
<script setup>
import TheWelcome from '../components/TheWelcome.vue'
import {getCurrentInstance, onMounted, onUnmounted, ref} from 'vue';
const { proxy } = getCurrentInstance()
const title = ref("默认为英文文档 Documentation")
// proxy.$bus.on会一直监听test有没有被emit
proxy.$bus.on("test", (msg)=>{
  console.log(msg)
  // 执行函数调用或者修改字段等
  title.value = msg
  // 也可以在这里边调用方法如下:
  // 方法名()
})
// 注意一定要在组件销毁时把事件监听对象销毁了,不然会引起内存泄漏
onUnmounted(()=>{
  proxy.$bus.off("test")
})
</script>

TheWelcome.vue的内容如下(截图截错了):

<script setup>
import WelcomeItem from './WelcomeItem.vue'
import DocumentationIcon from './icons/IconDocumentation.vue'
import ToolingIcon from './icons/IconTooling.vue'
import EcosystemIcon from './icons/IconEcosystem.vue'
import CommunityIcon from './icons/IconCommunity.vue'
import SupportIcon from './icons/IconSupport.vue'
// 通过属性接受参数
const props = defineProps({
  title:{
    type: String,
    required: true
  }
})

</script>

<template>
  <WelcomeItem>
    <template #icon>
      <DocumentationIcon />
    </template>
    <template #heading>{{props.title}}</template>

    Vue’s
    <a href="https://vuejs.org/" target="_blank" rel="noopener">official documentation</a>
    provides you with all information you need to get started.
  </WelcomeItem>

  <WelcomeItem>
    <template #icon>
      <ToolingIcon />
    </template>
    <template #heading>Tooling</template>

    This project is served and bundled with
    <a href="https://vite.dev/guide/features.html" target="_blank" rel="noopener">Vite</a>. The
    recommended IDE setup is
    <a href="https://code.visualstudio.com/" target="_blank" rel="noopener">VSCode</a>
    +
    <a href="https://github.com/johnsoncodehk/volar" target="_blank" rel="noopener">Volar</a>. If
    you need to test your components and web pages, check out
    <a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a>
    and
    <a href="https://on.cypress.io/component" target="_blank" rel="noopener"
      >Cypress Component Testing</a
    >.

    <br />

    More instructions are available in <code>README.md</code>.
  </WelcomeItem>

  <WelcomeItem>
    <template #icon>
      <EcosystemIcon />
    </template>
    <template #heading>Ecosystem</template>

    Get official tools and libraries for your project:
    <a href="https://pinia.vuejs.org/" target="_blank" rel="noopener">Pinia</a>,
    <a href="https://router.vuejs.org/" target="_blank" rel="noopener">Vue Router</a>,
    <a href="https://test-utils.vuejs.org/" target="_blank" rel="noopener">Vue Test Utils</a>, and
    <a href="https://github.com/vuejs/devtools" target="_blank" rel="noopener">Vue Dev Tools</a>. If
    you need more resources, we suggest paying
    <a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">Awesome Vue</a>
    a visit.
  </WelcomeItem>

  <WelcomeItem>
    <template #icon>
      <CommunityIcon />
    </template>
    <template #heading>Community</template>

    Got stuck? Ask your question on
    <a href="https://chat.vuejs.org" target="_blank" rel="noopener">Vue Land</a>, our official
    Discord server, or
    <a href="https://stackoverflow.com/questions/tagged/vue.js" target="_blank" rel="noopener"
      >StackOverflow</a
    >. You should also subscribe to
    <a href="https://news.vuejs.org" target="_blank" rel="noopener">our mailing list</a>
    and follow the official
    <a href="https://twitter.com/vuejs" target="_blank" rel="noopener">@vuejs</a>
    twitter account for latest news in the Vue world.
  </WelcomeItem>

  <WelcomeItem>
    <template #icon>
      <SupportIcon />
    </template>
    <template #heading>Support Vue</template>

    As an independent project, Vue relies on community backing for its sustainability. You can help
    us by
    <a href="https://vuejs.org/sponsor/" target="_blank" rel="noopener">becoming a sponsor</a>.
  </WelcomeItem>
</template>

没点击之前的效果:

在这里插入图片描述

点击按钮之后的效果

在这里插入图片描述


http://www.kler.cn/a/448423.html

相关文章:

  • 【信息系统项目管理师】高分论文:论信息系统项目的成本管理(车站设备智能化管理平台)
  • Nuc9 Truenas 和 Macmini4组雷电网桥 上传速度异常 1Mbp/s 解决
  • 用java造1万条数据
  • 拆解一个微型气泵了解工作原理
  • 基础爬虫案例实战
  • 网络安全防范
  • MySQL 主从复制与高可用
  • MongoDB(下)
  • 深度学习之目标检测——RCNN
  • 《Java核心技术I》Swing的组合框
  • MongoDB 介绍及 Java 实现基本操作
  • kafka详解
  • Gin-vue-admin(1):环境配置和安装
  • 管理系统、微信小程序类源码文档-哔哩哔哩教程同步
  • CV-OCR经典论文解读|An Empirical Study of Scaling Law for OCR/OCR 缩放定律的实证研究
  • 边缘智能网关助力打造建筑智慧消防物联网
  • 【CSS】line-height: 120% 和 line-height: 1.2有什么区别?
  • python面试篇-多并发详解(多线程,多进程,协成整理)---一篇搞定
  • 南京观海微电子----单片机的中断系统
  • 使用JavaScript获取商品详情接口:一个实用的指南
  • GO--堆(have TODO)
  • outlook smtp 发送邮件
  • Android-Glide缓存机制
  • Zookeeper 底层原理解析
  • 大小端存储的问题
  • mysql-主从同步与读写分离