What is the vue global event bus? What is the use? What problem is solved and how is it different from pinia?


concept

Basic Concept (What is it?)

  • Vue全局事件总线Is a mechanism for communication between components in Vue.js applications. It is basically a Vue instance used to pass events and data between different components of the application.

Core idea

  • vueMechanism for communication between components
  • 全局事件总线的工作原理是, you can trigger a custom event in one component, and then listen to this event in other components and perform corresponding operations. This allows different components to communicate with each other without having to pass data through props or other complex methods.

Core Features and Benefits (What are they used for?)

What problem was solved?

  • Resolve communication issues between parent and child components or between components that are not directly related.

What are the main advantages?

  • If you just need to pass some temporary data between different components or trigger some simple events, the global event bus is sufficient because it is lightweight and easy to use. Suitable for simple component communication needs.

Case presentation?

Passing Data-Case Demonstration

When you need to use the global event bus in your Vue.js application, 通常的做法是将全局总线$bus挂载到vue原型对象上use it in your components to fire and listen to events when needed. Here is a simple global event bus example:

First, register a global event bus in your Vue.js application. You can add the following code in main.js or similar entry file:

import Vue from 'vue'
import App from './App.vue'
import router from '@/routers/router'

Vue.config.productionTip = false


new Vue({
    
    
  router,
  render: h => h(App),
  beforeCreate() {
    
    
    // 挂载全局事件总线到vue原型对象上
    Vue.prototype.$bus = this
  }
}).$mount('#app')

Create a routing table router.js file and add the following content:

//作用是将指定的路由地址切换成对应的模块
// eslint-disable-next-line no-unused-vars
import Router from "vue-router"
// eslint-disable-next-line no-unused-vars
import Vue from "vue"
//在Vue中加载路由模块
Vue.use(Router)

const routes = [
    // 进入vue项目默认进入登录页面
    {
    
    
        path: "/",
        redirect: "/HelloWord"
    },
    {
    
    
        path: "/HelloWord",
        component: () => import("@/components/HelloWorld.vue"),
        meta: {
    
    
            skipAuthCheck: true // 添加一个标记,表示不需要进行身份验证检查
        }
    },
    {
    
    
        path: "/index",
        component: () => import("@/components/child.vue"),
        meta: {
    
    
            skipAuthCheck: true // 添加一个标记,表示不需要进行身份验证检查
        }
    },
]

const router = new Router({
    
    
    routes
});


// 导出vue路由表
export default router;

Now, you can use it in any component this.$busto trigger events and listen for events. For example, suppose you have two components, one that fires an event and another that listens for the event.

In the component that triggers the event:

<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="child">
    {
    
    {
    
    msg}}
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      msg: "小米加步枪",
    };
  },
  mounted() {
    
    
    console.log("进入child");
    // 组件挂载时触发自定义事件 传递数据this.msg
    this.$bus.$emit('message-sent', this.msg);
  },
};
</script>

In the component listening to the event:

<script>
<template>
  <div class="hello">
    <router-link to="/index"><button @click="sendMessage">购物</button></router-link>
  </div>
</template>

<script>
// 导入传递组件
import childComponent from '@/components/child.vue';
export default {
    
    
  name: 'HelloWorld',
  components: {
    
    
    // eslint-disable-next-line vue/no-unused-components
    childComponent,
  },
  methods: {
    
    
    sendMessage() {
    
    
      //监听一个自定义事件并处理
      this.$bus.$on('message-sent',(message) => {
    
    
        console.log(message);
        this.receivedMessage = message;
      })
    },
  }
}
</script>

In this example, when the user clicks a button in the component that triggers the event, it triggers a custom event named "message-sent" and passes the message data to the event-listening component, which after receiving the event update data.

This is a simple global event bus example for communication between components in a Vue.js application. You can extend this pattern to implement more complex communications based on your needs.

Delivering Events-Case Demonstration

When you need to deliver custom events in a Vue.js application, you can use Vue's custom event mechanism. Here's an example that demonstrates how to trigger a custom event in a parent component and listen and handle the event in a child component:

First, create a parent component (for example, Parent.vue):

<template>
  <div>
    <button @click="sendEvent">触发自定义事件</button>
    <Child @custom-event="handleCustomEvent" />
  </div>
</template>

<script>
import Child from './Child.vue';

export default {
      
      
  components: {
      
      
    Child,
  },
  methods: {
      
      
    sendEvent() {
      
      
      // 触发自定义事件,并传递数据
      this.$emit('custom-event', '这是自定义事件的数据');
    },
    handleCustomEvent(data) {
      
      
      // 处理从子组件接收到的事件数据
      console.log('接收到自定义事件:', data);
    },
  },
};
</script>

In the above code, the parent component this.$emittriggers a custom event named "custom-event" and passes some data.

Then, create a child component (for example, Child.vue):

<template>
  <div>
    <p>子组件</p>
  </div>
</template>

<script>
export default {
      
      
  mounted() {
      
      
    // 在子组件中监听自定义事件
    this.$parent.$on('custom-event', this.handleCustomEvent);
  },
  beforeDestroy() {
      
      
    // 在销毁子组件之前,取消对事件的监听
    this.$parent.$off('custom-event', this.handleCustomEvent);
  },
  methods: {
      
      
    handleCustomEvent(data) {
      
      
      // 处理父组件触发的自定义事件
      console.log('子组件接收到自定义事件:', data);
      // 可以在这里执行子组件的逻辑
    },
  },
};
</script>

In the child component, we access the parent component using this.$parent( vue is used to access specific properties of the parent component instance ) and use $onmethods to listen to custom events triggered by the parent component. In beforeDestroylifecycle hooks, cancel listening to events to avoid memory leaks.

Replenish:如果在路由跳转后你不想销毁之前的component可以使用<keep-alive></keep-alive>标签保持组件活跃

<keep-alive>
		<router-view></router-view>
</keep-alive>

Now, when the button in the parent component is clicked, it will trigger a custom event , and the child component will listen and handle this event , thereby realizing event delivery and processing.

This example demonstrates the basic pattern for passing custom events in Vue.js, and you can extend it as needed to meet more complex component communication needs.

What is the difference from pinia?

  • The global event bus and Pinia differ in the way data is transferred:
  1. Global event bus: 数据或事件通常是临时存储在内存中的, only passed between components, but not saved long-term. 当一个组件触发事件时,其他组件可以监听并获取这些事件的数据, but this data is not shared in persistent state between components.

  2. Pinia: Pinia is a state management library that allows you to define and manage global state in your application. Pinia的数据存储是持久的,保存在内存中,以供应用程序中的**所有组件**访问. This means you can share and maintain persistent state between different components, not just short-lived event data.

Therefore, Pinia is more suitable for scenarios that require long-term sharing and management of state, while the global event bus is more suitable for short-term, temporary data transfer between components. You can choose the appropriate method based on the specific needs of your project.

Guess you like

Origin blog.csdn.net/qq_58647634/article/details/133697231