Can you force Vue.js to reload/re-render?
Asked Answered
D

23

414

Just a quick question.

Can you force Vue.js to reload/recalculate everything? If so, how?

Dilettante answered 19/8, 2015 at 21:43 Comment(7)
Might get better support here github.com/vuejs/Discussion/issuesBologna
Great, didn't know about that discussion place. I'll try over there.Dilettante
Did you end up getting a response? I'm keen to know as well.Seigniorage
Don't remember exactly. But here's the issue I opened with some clues: github.com/vuejs/Discussion/issues/356Dilettante
I have v-for directive in the view and have use case when I manually swap two objects on that array. Vue doesn't automatically rerender template after this. I used workaround: just do any action with this array (do push empty object and then splice) - this triggers rerender. But this is special case.Silage
using vue's nextTick would re-renderedGlowing
i have same issue but with firebase token, the page need to refreshLuce
S
365

Try this magic spell:

vm.$forceUpdate();
//or in file components
this.$forceUpdate();

No need to create any hanging vars :)

Update: I found this solution when I only started working with VueJS. However further exploration proved this approach as a crutch. As far as I recall, in a while I got rid of it simply putting all the properties that failed to refresh automatically (mostly nested ones) into computed properties.

More info here: https://v2.vuejs.org/v2/guide/computed.html

Seka answered 14/11, 2016 at 10:45 Comment(8)
this really helped me when I was using it with a form wizard component in Vue. My form fields fields were loosing state though the data variables were intact. Now I am using this to refresh the views when I go back, I had to place it in setTimeout function.Costa
Note that in vue files you need 'this.$forceUpdate();'Elbertina
In some absolutely weird way $forceUpdate() never EVER worked for me on 2.5.17.Viridity
@AbanaClara $forceUpdate() never was a public method, I found it digging source code of Vue. And since it's usage never was the right way of Vue'ing, perhaps it could be stripped out. Cannot say for sure if it is still there, since I don't do front-end anymore.Seka
This does not help if you need to actually re-trigger the route, and it's guards. Lets say that your route fetches data, and inserts it into component props. Without reloading the entire page, how do you get vue router to refresh the route?Prudence
Computed properties worked for me but I had to add to define the whole object as computed in cases where it was an object with multiple nested value where some might be updated based on state. (i.e options object of a video player)Narcissus
Do you have to do that with later versions of vue.js as well?Pepillo
Just use Snabbdom on which Vue was based at the first place. Simply traverse the whole VDOM pure-functional hierarchy on any change you get. It's super fast if you don't have to compute state of a giant IDE/EDA/CAD on every state change.Windhoek
M
156

This seems like a pretty clean solution from matthiasg on this issue:

you can also use :key="someVariableUnderYourControl" and change the key when you want to component to be completely rebuilt

For my use case, I was feeding a Vuex getter into a component as a prop. Somehow Vuex would fetch the data but the reactivity wouldn't reliably kick in to rerender the component. In my case, setting the component key to some attribute on the prop guaranteed a refresh when the getters (and the attribute) finally resolved.

Muncy answered 12/2, 2018 at 20:44 Comment(4)
This is a neat little trick, it basically forces a re-instantiation of the component (mounted will be run, etc)Mayman
@Mayman I agree, it's probably not the "right' way to do things, but it is a fairly clean hack, for what it is.Muncy
this helpful. I use route full path as the key to rerender the same component when the route changes. :key="$route.fullPath"Fowler
I just came up with a pro hack: :key="'pro-hack-'+arr.length", causes it to refresh when a new item is added/removed from the array. I had a warzone condition where the slot content was not updating only when the component was currently scrolled max-rightEisenach
K
135

Please read this http://michaelnthiessen.com/force-re-render/

The horrible way: reloading the entire page
The terrible way: using the v-if hack
The better way: using Vue’s built-in forceUpdate method
The best way: key-changing on your component

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

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

I also use watch: in some situations.

Keynesianism answered 25/1, 2019 at 14:42 Comment(4)
The link doesn't actually show how to do it the horrible way, which is unfortunately what I need since my app is designed around navigating the horrible way. A simple URL to the current page doesn't seem to work, at least not in the app I'm dealing with, so I actually need instructions on how to do it the horrible way.Leakage
@WarrenDew Please follow: #3715547Keynesianism
I like the horrible way. Put this line in a watcher window.location.reload();Sear
In my case the key changes (meaning the function that change it is invoked) by the component does not re-render :(Forepaw
K
72

Try to use this.$router.go(0); to manually reload the current page.

Knowling answered 8/6, 2018 at 9:6 Comment(2)
Simpler: this.$router.go()Uralic
Actually @MariusAndreiana - the .go() function requires 1 non-optional parameterFrowst
Q
63

Why?

...do you need to force an update?

Perhaps you are not exploring Vue at its best:

To have Vue automatically react to value changes, the objects must be initially declared in data. Or, if not, they must be added using Vue.set().

See comments in the demo below. Or open the same demo in a JSFiddle here.

new Vue({
  el: '#app',
  data: {
    person: {
      name: 'Edson'
    }
  },
  methods: {
    changeName() {
      // because name is declared in data, whenever it
      // changes, Vue automatically updates
      this.person.name = 'Arantes';
    },
    changeNickname() {
      // because nickname is NOT declared in data, when it
      // changes, Vue will NOT automatically update
      this.person.nickname = 'Pele';
      // although if anything else updates, this change will be seen
    },
    changeNicknameProperly() {
      // when some property is NOT INITIALLY declared in data, the correct way
      // to add it is using Vue.set or this.$set
      Vue.set(this.person, 'address', '123th avenue.');
      
      // subsequent changes can be done directly now and it will auto update
      this.person.address = '345th avenue.';
    }
  }
})
/* CSS just for the demo, it is not necessary at all! */
span:nth-of-type(1),button:nth-of-type(1) { color: blue; }
span:nth-of-type(2),button:nth-of-type(2) { color: red; }
span:nth-of-type(3),button:nth-of-type(3) { color: green; }
span { font-family: monospace }
<script src="https://unpkg.com/vue@2"></script>

<div id="app">
  <span>person.name: {{ person.name }}</span><br>
  <span>person.nickname: {{ person.nickname }}</span><br>
  <span>person.address: {{ person.address }}</span><br>
  <br>
  <button @click="changeName">this.person.name = 'Arantes'; (will auto update because `name` was in `data`)</button><br>
  <button @click="changeNickname">this.person.nickname = 'Pele'; (will NOT auto update because `nickname` was not in `data`)</button><br>
  <button @click="changeNicknameProperly">Vue.set(this.person, 'address', '99th st.'); (WILL auto update even though `address` was not in `data`)</button>
  <br>
  <br>
  For more info, read the comments in the code. Or check the docs on <b>Reactivity</b> (link below).
</div>

To master this part of Vue, check the Official Docs on Reactivity - Change Detection Caveats. It is a must read!

Quinby answered 14/4, 2018 at 17:37 Comment(8)
Definitely agree that you should question this refresh requirement, but sometimes you just need the UI to re-render because the viewport has changed and you need to show different assets (as one example). The data may not have actually changed.Angkor
Why do you need to reload? In some cases resource files (stylesheets/js) cached by the browser need to be reloaded after a certain period of time. I had a stylesheet that needed to be reloaded after 7 days and if a user kept a tab open with a page access and came back after 7 days to navigate that page, the css was more than 7 days old.Kinin
@AchielVolckaert you probably have already found the answer, but yes, Vue.set() also works inside components.Quinby
@Angkor and @ Aurovrata, those are legitimate uses of refreshing, I agree. The questioning I posed is that people not rarely do the refreshing for the wrong reasons.Quinby
Perhaps you're just trying to fix a bug in a poorly designed web app that uses vue purely as a rendering tool, and for example reloads the entire application whenever it goes to the server, ignoring the client side application capabilities of vue. In the real world, you don't always have the time to fix every abomination you find.Leakage
There are situations that require a forced update. Example: an image component that points to the URL of the picture of the user profile. In the same page the user can submit a new picture and the image component should re-render to get the updated data. In this case, the URL of the image component does not change for the same user (i.e.: /images/profile/john-avatar.jpg).Sherer
Why do you need to reload? Switching translations <- because they are not driven by your data. They are a mess you do not want to muddy your scope, nor want it to maintain.Armijo
> Why? I'm trying to re-render a pure-functional components tree which destructures and maps a complex tree hierarchy passed from the root App component. Attempting to change one field doesn't trigger automatic re-render. Array elements and Object properties are added and removed in event handler and network response handlers, and I absolutely don't want to traverse the entire tree and tell Vue's reactive system imperatively what was added and removed. What's the point of reactivity at the first place then?..Windhoek
S
26

Sure .. you can simply use the key attribute to force re-render (recreation) at any time.

<mycomponent :key="somevalueunderyourcontrol"></mycomponent>

See https://jsfiddle.net/mgoetzke/epqy1xgf/ for an example

It was also discussed here: https://github.com/vuejs/Discussion/issues/356#issuecomment-336060875

Stream answered 18/8, 2018 at 14:34 Comment(0)
I
25

Use vm.$set('varName', value).

Look for details into Change_Detection_Caveats

Inconvincible answered 21/1, 2016 at 13:1 Comment(3)
"Page Not Found"Windhoek
Link updated for the old v2 documentation.Herald
Something to note: this is specific to Vue2. Vue3 solves this issue thanks to proxies, hence it's mostly not needed anymore nowadays.Herald
G
15

So there's two way you can do this,

  1. You can use $forceUpdate() inside your method handler i.e

<your-component @click="reRender()"></your-component>

<script>
export default {
   methods: {
     reRender(){
        this.$forceUpdate()
     }
   }
}
</script>
  1. You can give a :key attribute to your component and increment when want to rerender

<your-component :key="index" @click="reRender()"></your-component>

<script>
export default {
   data() {
     return {
        index: 1
     }
   },
   methods: {
     reRender(){
        this.index++
     }
   }
}
</script>
Gregson answered 14/2, 2020 at 13:58 Comment(0)
C
14
<my-component :key="uniqueKey" />

along with it use this.$set(obj,'obj_key',value) and update uniqueKey for every update in object (obj) value for every update this.uniqueKey++

it worked for me this way

Chromic answered 19/11, 2019 at 6:8 Comment(0)
M
13

In order to reload/re-render/refresh component, stop the long codings. There is a Vue.JS way of doing that.

Just use :key attribute.

For example:

<my-component :key="unique" />

I am using that one in BS Vue Table Slot. Telling that I will do something for this component so make it unique.

Misconduct answered 27/9, 2019 at 10:1 Comment(1)
Purges the entire DOM; all text edit boxes lose state. Very annoying...Windhoek
T
7

Dec, 2021 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 "value" with an array to :key="$route.fullPath" and change "value". So it becomes :key="[$route.fullPath, value]" and we need to change "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 problem of Vue for now.

Trail answered 20/9, 2021 at 23:44 Comment(0)
C
6

Using v-if directive

<div v-if="trulyvalue">
  <component-here />
</div>

So simply by changing the value of trulyvalue from false to true will cause the component between the div to rerender again

Chapnick answered 8/3, 2018 at 20:56 Comment(1)
In my opinion this is cleanest way to reload component. Altough in created() method You can add some initialization stuff.Hyps
T
4

This has worked for me.

created() {
    EventBus.$on('refresh-stores-list', () => {
        this.$forceUpdate();
    });
},

The other component fires the refresh-stores-list event will cause the current component to rerender

Taitaichung answered 22/2, 2019 at 8:39 Comment(1)
And where exactly does EventBus come from? It does not exist.Oubre
I
4
<router-view :key="$route.params.slug" />

Just use key with your any params its auto reload children..

Innutrition answered 22/4, 2019 at 9:31 Comment(2)
try to give a detailed information about your solution. add your code ,highlight the keywordsNorthington
Thanks, this worked for me. Handy when using sub-routes and you want to reload the content based on different routes.Harvest
P
3

Worked for me

    data () {
        return {
            userInfo: null,
            offers: null
        }
    },

    watch: {
        '$route'() {
            this.userInfo = null
            this.offers = null
            this.loadUserInfo()
            this.getUserOffers()
        }
    }
Predominance answered 20/6, 2019 at 21:33 Comment(1)
This is the way, I was facing similar issue with a paginated view using tags to filter the query, and navigating through tags didn't refresh the component albeit using :key=tag.idGilbertina
E
2

I found a way. It's a bit hacky but works.

vm.$set("x",0);
vm.$delete("x");

Where vm is your view-model object, and x is a non-existent variable.

Vue.js will complain about this in the console log but it does trigger a refresh for all data. Tested with version 1.0.26.

Enhanced answered 3/9, 2016 at 22:11 Comment(0)
T
2

The approach of adding :key to the vue-router lib's router-view component cause's fickers for me, so I went vue-router's 'in-component guard' to intercept updates and refresh the entire page accordingly when there's an update of the path on the same route (as $router.go, $router.push, $router.replace weren't any help). The only caveat with this is that we're for a second breaking the singe-page app behavior, by refreshing the page.

  beforeRouteUpdate(to, from, next) {
    if (to.path !== from.path) {
      window.location = to.path;
    }
  },
Terryl answered 9/11, 2020 at 6:49 Comment(0)
C
1

Add this code:

this.$forceUpdate()
Calise answered 20/4, 2020 at 5:32 Comment(2)
This does not work if you need the actual route to re-trigger, which triggers data fetching in your route guards to fetch data for component properties that vue-router inserts.Prudence
I use Quasar and it has Vue-Router as a nailed hardcoded dependency. Is that what not letting $forceUpdate() do its work?...Windhoek
M
1

Except page reload method(flickering), none of them works for me (:key didn't worked).

and I found this method from old vue.js forum which is works for me:

https://github.com/vuejs/Discussion/issues/356

<template>
    <div v-if="show">
       <button @click="rerender">re-render</button>
    </div>
</template>
<script>
    export default {
        data(){
            return {show:true}
        },
        methods:{
            rerender(){
                this.show = false
                this.$nextTick(() => {
                    this.show = true
                    console.log('re-render start')
                    this.$nextTick(() => {
                        console.log('re-render end')
                    })
                })
            }
        }
    }
</script>
Miff answered 30/5, 2020 at 10:12 Comment(0)
G
0

For anyone still looking around, there's a package for this now.

https://github.com/gabrielmbmb/vuex-multi-tab-state

All I had to do was install it and add it to my plugins in main.ts (as it shows on that page) and it did exactly what I wanted.

Gunas answered 3/2, 2022 at 16:50 Comment(0)
S
0

If your URL changes as well when if the component is loaded you can just use it in the :key attribute. This works especially well if you use it on the router-view tag directly. And this commes with the added benedit of the key being a value that is actually tied to the content of the page instead of just some random number.

<router-view :key="this.$route.path"></router-view>
Shlomo answered 24/8, 2022 at 14:6 Comment(0)
O
0

If you are using router-view or Vue Router, you can directly use the key feature

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

This will tell the router view to re-render the page every time the path is changed.

Ortegal answered 2/11, 2022 at 8:31 Comment(0)
D
0
this.$router.go()

this.$forceUpdate(); doesnt work with Vue3

Distrust answered 18/4 at 11:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.