Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue router reloading the current route

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?

like image 384
user3581438 Avatar asked Apr 05 '19 03:04

user3581438


1 Answers

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.

like image 144
Riddhi Avatar answered Nov 12 '22 14:11

Riddhi