background

In the process of using Vue to do background management system, it is necessary to realize the parameter transfer between components. The Bus mode is very simple and convenient, but I encountered a strange phenomenon. When I click the menu area, I need to display the operation navigation in the header and display it in the content area. The result is no response in the header area. Now I will introduce how Vue3.0 integrates Bus and replay the whole process of the problem.

Vue3.0 integration Bus

  • The Bus mode after Vue to 3.0 changed to mitt. 2.0 is done by creating an empty Vue as the bus.
  • Use emit to register emitt(“type”,”event”); The first parameter can be interpreted as the event name, and the second parameter is usually a parameter.
  • Use on to listen, on(“type”, “handler” =>{here is the operation logic}); The first parameter corresponds to the first parameter above, indicating an event.
  • Emitt and ON come in pairs, one initiating and one receiving.
  • $emitt; $on; $emitt
  • The receiver can be multiple components, and the desired data can be retrieved as long as the first parameter matches, which is really convenient and an advantage of Vue.

Method 1: Global import

  • First install mitt
cnpm install --save mitt
Copy the code
  • Introduced in main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
// introduce here
import mitt from "mitt";

const app = createApp(App);
app
  .use(store)
  .use(router)
  .mount("#app");
// initialize here
app.config.globalProperties.$bus = mitt();
Copy the code
  • Page, because it is global, so in the use of the page do not need to introduce, directly use. The code is as follows:
  • Originator: My example is initiated in the selected method.

  • Mounted is not in method. If you use WebStorm, you will not get an error. This bug is very difficult to troubleshoot.

Method 2: Import on demand, where that component is needed, which I personally recommend.

  • Create a new package under SRC, name it bus, and create bus.js

  • Mitt is introduced into bus.js, and bus is declared externally. You can directly introduce bus in the page of use.
import mitt from "mitt";

const bus = mitt();

export default bus;
Copy the code
  • Initiator: Use the difference shown in the code

  • Receiver:

conclusion

  • Vue3.0 makes it clear that there are two ways to introduce and reference a Bus correctly
  • I also shared with you a problem THAT I had with writing
  • You also need to be very careful about the life cycle
  • I don’t have a problem with overexecution, but more on that later
  • If it helps you, click on it.