This page looks best with JavaScript enabled

Reload Component based on Routes in Vue

 ·   ·  ☕ 2 min read

If two links in your Vue application point to the same view, clicking those links one after the other may not result in data being refreshed from server.

Imagine you have the same view for two different links -

  • My account
  • All account

Both links will point to Account.vue. You will have a router file like so..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ./router.js

import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

export default new Router({
    routes: [
    {
      path: "/my-account",
      name: "my-account",
      component: () => import("./views/Account.vue"),
      props: { authMode: "my" }
    },
    {
      path: "/all-account",
      name: "all-account",
      component: () => import("./views/Account.vue"),
      props: { authMode: "all" }
    },
});

Example code for router is picked from the demonstration of how to implement role-based data filters in Vue.

The above functionality does not work as expected if you have access to both ‘My Accounts’ and ‘All Accounts’.

  • If you click on My Accounts, you will see accounts assigned to you. If you click on ‘All Accounts’ later, you will not see any refreshed query being sent to server
  • The above is true even if you reverse the order of clicking the said links
  • The functionality works as expected if you click on another link (say Profile) before clicking on ‘All Accounts’

The reason for this behaviour is simple - Vue does not reload components and refresh queries if the same component is being loaded as part of a different route.

The route does change, but the component and data remain the same.

The solution is quite simple too - just include a key to the router-view.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<template>
  <div>
    <Toolbar></Toolbar>
    <v-app>
      <v-content>
        <router-view :key="$route.fullPath"></router-view>
      </v-content>
    </v-app>
  </div>
</template>

Now any change in route will result in change to the key. This results in router-view and component being refreshed with UI elements and data - regardless of whether you have the same view across the routes.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things