Vue-router reload components

35,408

Solution 1

Partially thanx to this: https://forum.vuejs.org/t/vue-router-reload-component/4429

I've come up with a solution that works for me:

First I added a new function to jQuery which is used to retrigger bootstrap animation when the component loads.

$.fn.redraw = function(){
    return $(this).each(function(){
        var redraw = this.offsetHeight;
    });
};

In component:

export default{
        created:function(){
            this.onCreated();
        },
        watch: {
            '$route' (to, from) {
                //on route change re run: onCreated
                this.onCreated();

                //and trigger animations again
                $("#breadcrumbsCurrentProject").find(".animated").removeClass("fadeIn").redraw().addClass("fadeIn");
            }
        }
}

I call the onCreated(); method when the component loads and when the route reloads or the ID of the same route changes but the component stays the same I just call the method again. This takes care of the new data.

As for re triggering bootstrap animations I use redraw(); function I add to jQuery right on the start of the app. and this re triggers the animations on URL change:

$("#breadcrumbsCurrentProject").find(".animated").removeClass("fadeIn").redraw().addClass("fadeIn");

Solution 2

I was facing the same problem. I will quote a found answer, which is really simple and great. The simplest solution is to add a :key attribute to :

<router-view :key="$route.fullPath"></router-view>

This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.

Solution 3

It looks like you are using vue-router.

I don't have your code, but I can show you how I handled this. See named-views.

Here is my router-map from my bundle.js file:

const router = new VueRouter({
routes: [
    { path: '/',
      components: {
        default: dashboard,
        altside: altSide,
        toolbar: toolbar
      },
    },
    { path: '/create',
      components: {
        default: create,
        altside: altSide,
        toolbar: toolbar
      },
    },
    { path: '/event/:eventId', 
        name: 'eventDashboard',
        components: { 
            default: eventDashboard,
            altside: altSide,
            toolbar: eventToolbar,
        },
        children: [
            { path: '/', name: 'event', component: event },
            { path: 'tickets', name: 'tickets', component: tickets},
            { path: 'edit', name: 'edit', component: edit },
            { path: 'attendees', name: 'attendees', component: attendees},
            { path: 'orders', name: 'orders', component: orders},
            { path: 'uploadImage', name: 'upload', component: upload},
            { path: 'orderDetail', name: 'orderDetail', component: orderDetail},
            { path: 'checkin', name: 'checkin', component: checkin},
        ],
    }
]
})

I have named-views of "default", "altside" and "toolbar" I am assigning a component to the named view for each path.

The second half of this is in your parent component where you assign the name

<router-view  name="toolbar"></router-View>   

Here is my parent template:

<template>

    <router-view class="view altside" name="altside"></router-view>
    <router-view class="view toolbar" name="toolbar"></router-view>
    <router-view class="view default"></router-view>
</template>

So, what I've done is I've told the parent template to look at the named-view of the router-view. And based upon the path, pull the component I've designated in the router-map.

For my '/' path toolbar == the toolbar component but in the '/create' path toolbar = eventToolbar component.

The default component is dynamic, which allows me to use child components without swapping out the toolbar or altside components.

Solution 4

Feb, 2022 Update:

You can force-reload components by adding :key="$route.fullPath".

For Child Component:

<Child :key="$route.fullPath" />

For router-view tag:

<router-view :key="$route.fullPath" />

However, :key="$route.fullPath" only can force-reload the components of the different route but not the components of the same route. To be able to force-reload the components of the same route as well, we need to add a value to :key= and change the value.

*We can assign Array to :key=.

<template>
  <Child 
    :key="[$route.fullPath, value]" // Can assign "Array" to ":key="
    @childReload="reload" // Call @click="$emit('childReload')" in   
  />                      // Child Component to increment the value.
</template> 

    OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR

<template>
  <router-view 
    :key="[$route.fullPath, value]" // Can assign "Array" to ":key="
    @routerViewReload="reload" // Call @click="$emit('routerViewReload')"
  />                           // in Child Component to increment the value.
</template>
    
<script>
export default {
  name: "Parent", components: { Child, },
  data() {
    return {
      value: 0,
    };
  },
  methods: {
    reload() {
      this.value++;
    }
  }
}
</script>

However, to keep using both $route.fullPath and value causes some error sometimes so only when some event like Click happens, we use both $route.fullPath and value. Except when some event like Click happens, we always need to use only $route.fullPath.

This is the final code:

<template>
  <Child 
    :key="state ? $route.fullPath : [$route.fullPath, value]"
    @childReload="reload" // Call @click="$emit('childReload')" in
  />                      // Child Component to increment the value.
</template>
    
    OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR
    
<template>
  <router-view 
    :key="state ? $route.fullPath : [$route.fullPath, value]"
    @routerViewReload="reload" // Call @click="$emit('routerViewReload')" in
  />                           // Child Component to increment the value.
</template>
        
<script>
export default {
  name: "Parent", components: { Child, },
  data() {
    return {
      state: true,
      value: 0,
    };
  },
  methods: {
    reload() {
      this.state = false;
      this.value++;
      this.$nextTick(() => this.state = true);
    }
  }
}
</script>

Unfortunately, there are no simple ways to force-reload components properly in Vue. That's the big problem of Vue for now.

Solution 5

This is what I came up with:

import ProjectMain from './templates/ProjectMain.vue';
import SidebarProject from './templates/SidebarProject.vue';

//now shallow copy the objects so the new object are treated as seperatete .vue files with: $.extend({}, OriginalObject); //this is so I don't have to create basically the same .vue files but vue-router will reload those files because they are different

const ProjectMainA = $.extend({}, ProjectMain);
const ProjectMainB = $.extend({}, ProjectMain);
const ProjectMainC = $.extend({}, ProjectMain);
const SidebarProjectA = $.extend({}, SidebarProject);
const SidebarProjectB = $.extend({}, SidebarProject);
const SidebarProjectC = $.extend({}, SidebarProject);

const routes = [
{
path: "/myapps/newproject",
components: {
default: ProjectMainA,
"breadcrumbs": BreadcrumbsNewProject,
"sidebar": SidebarProjectA
}
},
{
path: "/myapps/:id",
components: {
default: ProjectMainB,
"breadcrumbs": BreadcrumbsCurrentProject,
"sidebar": SidebarProjectB
}
},
{
path: "/myapps/newversion/:id",
components: {
default: ProjectMainC,
"breadcrumbs": BreadcrumbsNewVersion,
"sidebar": SidebarProjectC
}
}
];

This basically tricks the vue-router into thinking he's loading different .vue components, but they are actually the same. So I get everything I want: reloading of the component, animation, life cycle, and I don't have to write multiple similar or the same components. What do you think, I'm just not sure if this is the best practice.

Share:
35,408
dari0h
Author by

dari0h

Updated on July 14, 2022

Comments

  • dari0h
    dari0h almost 2 years

    I have a few routes that each load 3 components. Two of the components are the same on all routes. When I move between those routes I want to pass new data and on some init event of the component I want to fill the data of that component so it reflects on the UI. Also I want to retrigger bootstrap animations of components being loaded. How would I go about doing that. Because right now, I don't know where in the component lifecycle would I fetch the data and rerender the component with this new data. Concretly in myapps/1 and /newapp/ I have a main view component and a sidebar component. In the /newapp/ URL I want all icons on the sidebar to be red (nothing on the main view has been filled) and the main view should be empty. On the myapps/1 I want to load the data from the server into the main view and if it's all filled I want icons on the sidebar to be green. What now happens I load myapps/1, click on the second item in the sidebar and the main view changes to the second view. Then I router.push("/newapp/); and sidebar stays on the second item and second main view. So router.push("/myapps/"); doesn't reload my sidebar and my main view.

    EDIT:

    Here you see my routes, sidebars and default are the same.

    const routes = [
      {
        path: "/myapps/newproject",
        components: {
          default: ProjectMain,
          "breadcrumbs": BreadcrumbsNewProject,
          "sidebar": SidebarProject,
         }
      },
      {
        path: "/myapps/:id",
        components: {
          default: ProjectMain,
          "breadcrumbs": BreadcrumbsCurrentProject,
          "sidebar": SidebarProject,
        }
      },
      {
        path: "/myapps/newversion/:id",
        components: {
          default: ProjectMain,
          "breadcrumbs": BreadcrumbsNewVersion,
          "sidebar": SidebarProject,
        }
      }
    ];
    

    This is my ProjectMain.vue

    <template>
      <div class="wrapper wrapper-content">
        <component :is="currentProjectMain"></component>
      </div>
    </template>
    

    This is my router-view in index.html:

    <router-view name="sidebar"></router-view>
    

    And I have another one in index.html, the default one:

    <router-view></router-view>
    

    When I click on some item on Sidebar i emit event to the ProjectMain to switch out the component. So like this: In Sidebar:

    eventBus.$emit("currentProjectMainChanged", "appOverview");
    

    or

    eventBus.$emit("currentProjectMainChanged", "appSettings");
    

    And than in ProjectMain:

    eventBus.$on("currentProjectMainChanged", function(data) {
      if(data === "appOverview") {
        self.currentProjectMain = CurrentProjectAppOverview;
      }else if(data === "appSettings") {
        self.currentProjectMain = CurrentProjectSettings;
      }
    });
    

    If I got to "/myapps/:id". It loads the sidebar and ProjectMain and I get a little animation of the sidebar and the ProjectMain with this bootstrap classes: <div class="animated fadeInUp"> and both components got through the entire lifecycle.

    By default appOverview is selected in sidebar and CurentProjectAppOverview.vue is loaded as a component in ProjectMain. Than I click on appSettings in the sidebar and class is added to that item in the sidebar to mark it as selected and in the ProjectMain CurrentProjectSettings.vue is loaded as a component.

    But then in the breadcrumbs I have a button to go to "/myapps/newversion/:id" Here is the problem. When I click to go to "/myapps/newversion/:id" (router.push("/myapps/newversion/" + id);) the second item on the sidebar remains selected (appSettings) and in ProjectMain CurrentProjectSettings.vue remains loaded, and I don't get the bootstrap animation of the sidebar and ProjectMain, and the components don't go through their lifecycle.

    What I want here when I click the button to go to "/myapps/newversion/:id" is my bootstrap animation (<div class="animated fadeInUp">), I want the Sidebar and ProjectMain to go through their entire lifecycle. And I want the default item to be selected on the sidebar (so appOverview) and default component to be loaded in ProjectMain (so CurentProjectAppOverview.vue).

    There are colored buttons for the each item in the sidebar. If I go to "/myapps/newversion/:id" from "/myapps/:id", I want to load the data from the server into CurrentProjectAppOverview.vue and if all data is filled I want the button on the sidebar to be green and if not it should be red.

    So In short when moving between this two routes I want to be able to load data and fill the fields I want, and I want bootstrap animation and default views to be selected and loaded and they should go through their entire lifecycle. Now router just reuses them as they are.

    So something like "ReloadComponent: true", or destroy and recreate component.

    I could duplicate SidebarProject.vue and ProjectMain.vue and rename them and in each route load basically a copy but that would mean I have to write the same code in different .vue files.

    Before there was an option to set YouComponent.route.canReuse to false, which would do what I want, I think, but it is removed in the newest version.

  • Ulysse Mizrahi
    Ulysse Mizrahi almost 7 years
    Another thing you can do is use the built-in beforeRouteEnter function on your component in order to intercept the route change
  • Gkiokan
    Gkiokan about 5 years
    Funny fact, I am still looking for my own answer to fix this issue on newer projects even it's so simple. This thing should be in the docs of Vue and it is a essential must know thing.
  • Alexander Kim
    Alexander Kim over 4 years
    This is not a good workaround, because key must be defined by a variable inside v-for.
  • Douglas Gaskell
    Douglas Gaskell over 4 years
    A bit absurd that vue router does not have an explicit way to reload a component. There are many uses cases, such as when the component relies on a store state that is set by the route change. Having a mess of logic in beforeChange is just that, a mess, and isn't extendable at all...
  • dari0h
    dari0h about 4 years
    Sometimes even this isn't enough. Sometimes you want to stay on the same path and reload the component e.g. you want to pass in a new prop and then reload a component. In those cases, I added an additional variable to the :key which I update at will and trigger rerender whenever: :key="$route.fullPath + $store.state.reloadMainComponentKey"