10

Without reloading the whole page I need to reload the current route again (Only a component reload) in a vue app.

I am having a path in vue router like below,

{
  path: "/dashboard",
  name: "dashboard",
  component: loadView("Dashboard"),

},

When user clicks on the Dashboard navigation item user will be redirected to the Dashboard page with vue router programmatic navigation

this.$router.push({ name: "dashboard" });

But when user already in the dashboard route and user clicks the Dashboard nav item again nothing happens. I think this is vue router's default behaviour. But I need to force reload the Dashboard component (Not to refresh the whole page).

I can't use beforeRouteUpdate since the router is not updated. Also I have tried the global before guards like beforeEach. But it is also not working.

How can I force reload the dashboard component without reloading the whole page?

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34
user3581438
  • 350
  • 1
  • 4
  • 8

2 Answers2

4

It can be done in two ways.

1) Try doing vm.$forceUpdate(); as suggested here.

2) You can take the strategy of assigning keys to children, but whenever you want to re-render a component, you just update the key.

<template>
  <component-to-re-render :key="componentKey" />
</template>

<script>
export default {
  data() {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender() {
      this.componentKey += 1;  
    }
  }
}
</script>

Every time that forceRerender is called, the prop componentKey will change. When this happens, Vue will know that it has to destroy the component and create a new one.

What you get is a child component that will re-initialize itself and “reset” its state.

Ryan
  • 29
  • 1
  • 4
Riddhi
  • 2,174
  • 1
  • 9
  • 17
0

Not mentioned here, but as the offered solutions require a lot of additional work just to get the app to render correctly, which imo is a brittle solution.. we have just implemented another solution which works quite well..

Although it is a total hack.

    if (this.$route.name === redirect.name) {
      // this is a filthy hack - the vue router will not reload the current page and then have vue update the view.
      // This hack routes to a generic page, then after this has happened the real redirect can happen
      // It happens on most devices too fast to be noticed by the human eye, and in addition does not do a window
      // redirect which breaks the mobile apps.
      await this.$router.push({
        name: RouteNames.ROUTE_REDIRECT_PLACEHOLDER
      });
    }

... now continue to do your normal redirect.

Essentially, redirect to a placeholder, await the response but then immediately continue to another page you actually wanted to move toward