Questions about the data response used by the vue global event bus

You can see this, which means that you still know the basic use of global events, so I won’t say much about the specific use. Let me tell you, the biggest doubt you may encounter, of course, is also the problem encountered in my project.

Problem Description

I have a jump method on the homepage:

 toMessage() {
      this.$router.push("/message");
      this.$bus.$emit('getms','hhhahaha')
    },

Then the page mounted after the jump:

this.$bus.$on('getms',(res)=>{
          console.log('我是message接受的信息', res)
        })

I think that if the jump of the page carries a large amount of data, it is a bit troublesome to carry parameters through the route, and the code is not beautiful. If you use vueX, you don't think it's very good. After all, for such a small demand, there is no need to associate it with vuex. So I want to pass the global event bus.

If you Baidu, 80's teachings are all about using the simple method of mounting to the prototype, and the scenarios they use can perfectly trigger and receive data. When you actually operate it, it will be another "disaster".

If you observe carefully, the situation I am talking about is that the two pages that jump through routing belong to two sibling elements of different pages. Here comes the problem,

When entering the page to be accepted for the first time, no data was received at all. And when you go back to the home page and enter again, the data will appear.

Solution

When emitting, use a timer to delay the trigger, because when $emit is triggered, $on must already exist.

this.$router.push("/message");
setTimeout(() => {
this.$bus.$emit('getms','hhhahaha')
}, 1000);

Before the route jumps, it is triggered in beforeDestroy, and after the route jumps, the new page created is received, which is

beforeDestroy() {
    this.$bus.$emit('getms','hhhahaha')
  },
created() {
    this.$bus.$on('getms',(res)=>{
        console.log('我是message接受的信息', res)
      })
  },
  1. Data received multiple times can destroy the event bus in the beforeDestory life cycle

beforeDestroy(){
    this.$bus.$off('getms');
  },

Of course, you can also perform destruction operations in destroyed and beforeRouteLeave.

Guess you like

Origin blog.csdn.net/qq_52856519/article/details/129261328