[Vuejs]-How to write a single piece of code running both on route A (mounted hook) and also when arriving at route A?

0👍

This technique is really needed only in two cases – multiple routes are using same component or dynamic routes (with parameters) …see the docs

In this cases when the new route is using same component as the old route, Vue Router will just reuse existing component instance.

  1. You can place a key on router-view and disable this behavior. Your site will be less effective but you can get rid of $route watcher
<router-view :key="$route.fullPath" />
  1. Other option is to change watcher definition like this:
watch: {
    $route: {
      immediate: true,
      handler: function(to, from) {
        console.log(`Route changing from '${from}' to '${to}'`);
      }
    }
  }

Vue will call watcher handler on route changes but also when the component is created (so you can remove the code in lifecycle hook)

Leave a comment