287

Just a quick question.

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

Kick Buttowski
  • 6,371
  • 12
  • 34
  • 54
Dave
  • 10,605
  • 9
  • 40
  • 52

19 Answers19

288

Try this magic spell:

vm.$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://vuejs.org/v2/guide/computed.html

Boris Mossounov
  • 3,264
  • 2
  • 12
  • 11
  • 4
    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. – Jimmy Ilenloa Aug 18 '17 at 18:13
  • 52
    Note that in vue files you need 'this.$forceUpdate();' – Katinka Hesselink Jan 03 '19 at 09:07
  • 1
    This works great for updating a after a lengthy axios call. – AlfredBr Jan 15 '19 at 17:14
  • 9
    In some absolutely weird way `$forceUpdate()` never EVER worked for me on 2.5.17. – Abana Clara Feb 25 '19 at 07:30
  • 2
    @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. – Boris Mossounov Feb 26 '19 at 12:29
  • 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? – Douglas Gaskell Aug 13 '20 at 23:57
106

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.

Brian Kung
  • 2,817
  • 3
  • 16
  • 26
62

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.

H6.
  • 26,822
  • 12
  • 70
  • 78
Yash
  • 4,958
  • 1
  • 31
  • 23
  • 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. – Warren Dew Dec 09 '19 at 04:53
  • @WarrenDew Please follow: https://stackoverflow.com/questions/3715047/how-to-reload-a-page-using-javascript – Yash Jan 18 '20 at 02:08
  • For me, the Michael Thiessen’s tip is the best of all. – Magno Alberto Feb 12 '21 at 18:41
58

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"></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!

acdcjunior
  • 114,460
  • 30
  • 289
  • 276
  • 2
    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. – the_dude_abides Aug 28 '18 at 23:20
  • 1
    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. – Aurovrata Nov 27 '18 at 10:43
  • @AchielVolckaert you probably have already found the answer, but yes, `Vue.set()` also works inside components. – acdcjunior Mar 22 '19 at 21:44
  • 1
    @the_dude_abides 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. – acdcjunior Mar 22 '19 at 21:45
  • 1
    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. – Warren Dew Dec 09 '19 at 04:48
  • 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). – Alexandre V. Feb 09 '20 at 10:57
  • Why do you need to reload? Switching translations – Daniel ZA May 01 '20 at 11:11
45

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

Poy Chang
  • 748
  • 1
  • 8
  • 12
24

Use vm.$set('varName', value). Look for details into Change_Detection_Caveats.

denis.peplin
  • 8,722
  • 3
  • 42
  • 51
17

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

mgoetzke
  • 634
  • 4
  • 13
13
<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

10

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>
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Shahrukh Anwar
  • 2,004
  • 1
  • 18
  • 20
6

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.

IlGala
  • 3,043
  • 3
  • 31
  • 46
Felix Labayen
  • 131
  • 2
  • 2
5

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

Geoff
  • 4,505
  • 14
  • 65
  • 156
  • 1
    In my opinion this is cleanest way to reload component. Altough in created() method You can add some initialization stuff. – Piotr Żak Oct 07 '18 at 15:32
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

Eric Aya
  • 68,765
  • 33
  • 165
  • 232
sean717
  • 9,395
  • 17
  • 55
  • 78
3

just add this code:

this.$forceUpdate()

GoodLuck

Rahman Rezaee
  • 679
  • 7
  • 18
  • 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. – Douglas Gaskell Aug 13 '20 at 23:56
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.

Laszlo the Wiz
  • 484
  • 4
  • 14
2

Worked for me

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

    watch: {
        '$route'() {
            this.userInfo = null
            this.offers = null
            this.loadUserInfo()
            this.getUserOffers()
        }
    }
tuwilof
  • 21
  • 2
1
<router-view :key="$route.params.slug" />

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

linktoahref
  • 6,570
  • 3
  • 20
  • 45
0

I had this issue with an image gallery that I wanted to rerender due to changes made on a different tab. So tab1 = imageGallery, tab2 = favoriteImages

tab @change="updateGallery()" -> this forces my v-for directive to process the filteredImages function every time I switch tabs.

<script>
export default {
  data() {
    return {
      currentTab: 0,
      tab: null,
      colorFilter: "",
      colors: ["None", "Beige", "Black"], 
      items: ["Image Gallery", "Favorite Images"]
    };
  },
  methods: {
    filteredImages: function() {
      return this.$store.getters.getImageDatabase.filter(img => {
        if (img.color.match(this.colorFilter)) return true;
      });
    },
    updateGallery: async function() {
      // instance is responsive to changes
      // change is made and forces filteredImages to do its thing
      // async await forces the browser to slow down and allows changes to take effect
      await this.$nextTick(function() {
        this.colorFilter = "Black";
      });

      await this.$nextTick(function() {
        // Doesnt hurt to zero out filters on change
        this.colorFilter = "";
      });
    }
  }
};
</script>
Jason
  • 414
  • 5
  • 9
0

sorry guys, 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>
sailfish009
  • 1,790
  • 1
  • 17
  • 26
0

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;
    }
  },
john-raymon
  • 101
  • 4
  • 16