Lifecycle hooks not working properly in order After migration from vu2 to vue3

155 Views Asked by At

The issue is when I switch from Route 1 to Route 2 then First "created" of route2 being called after that "unmounted" of route1. Actually it should be like first "unmounted" of Route1 should call after that "created" of Route1

I am using a common store in two routes. And registering and deregistering those stores in "created" and "unmounted" in all routes.

Route 1-

created() {
this.registerStore('Store1', Store1);
}
unmounted() {
this.unregisterStore('Store1');
}

Here Store1 is a common store in Route2.

Route 2 -

created() {
this.registerStore('Store2', Store2);
this.registerStore('Store1', Store1);
}
unmounted() {
this.unregisterStore('Store2');
this.unregisterStore('Store1');
}

Now the issue is when I switch from Route 1 to Route 2 then First "created" of route2 being called after that "unmounted" of route1. So in this case My store1 first register and then unregister because of that my Page is getting error on Route2 where using Store1

So I am not able to use common store in that case and separated stores.

1

There are 1 best solutions below

0
yoduh On

It's my observation that a new component's created hook runs before an old component's unmounted hook in Vue 2, same as Vue 3, and is also backed up by this older answer on SO.

Regardless, this type of logic should be centralized so conflicts of this type can be avoided. Something like the beforeEnter guard or beforeEach guard could unregister and register stores as needed based on the component you're leaving from and the component you're entering to

beforeEnter example:

{
    path: '/route2',
    component: Component2,
    beforeEnter: (to, from) => {
      if (from.path === '/route1') {
        unregisterStore('Store1');
      }
      registerStore('Store2', Store2);
      registerStore('Store1', Store1);
      // accept the navigation
      return true
    },
},

Logic can perhaps be simplified (not sure if unregistering then re-registering immediately is necessary for your use case).