Vuejs not triggering mounted after user pressed back on his browser

Viewed 4983

On my vuejs application there is a dashboard, where the user can click a button that send him to /room (router.push("/room");).

When the user arrive on the page, the "mounted" function is triggered and a simple console.log is emited. That works.

mounted() {
    console.log("room mounted");
}

If the user press the "back" button of his browser and go back to the dashboard, he can click the button again to join the room, except this time, the "mounted" function is not triggered.

Is there a way to make this works ?

Thank you.

2 Answers

In response to a part of your response to the answer below,

what I'm looking for is when I click again on the button that trigger the router.push("/room"), because when I'm redirected, mounted nor updated` are called.

To solve your problem, you can watch the $route object, by doing

watch: {
  '$route' () {
     // this will be called any time the route changes
   }
},

This is expected behavior in Vue Router according to this issue on the Vue Router GitHub repo:

This is expected behaviour, Vue re-uses components where possible.

You can use the beforeRouteUpdatehook to react to a route switch that uses the same component.

Navigating "back" to an already-mounted component won't trigger a subsequent mounting of the component. To see which lifecycle hooks are triggered on Route Update, you can look at this blog post (scroll down to the Lifecycle Hooks diagram).

The situation you're running into is the "Client Update" column, where mounted is not called, but update is. In general, I tend to utilize parallel code in both beforeRouteEnter and beforeRouteUpdate. Sadly, it's a bit repetitive.

Related