Search code examples
vue.jsbuttoncomponentsrendervue-reactivity

Vue rerender component on reset button


I have a reset button which reset the state to the initial values. I need to rerender the component with currentTab is there any bet way to do it?

<button @click="resetData">reset</button>

<keep-alive>
    <component :is="currentTab"></component>
</keep-alive>

methods: 
resetData() {
    this.$store.dispatch('resetData')
    // re-render component based on the currentTab
    ??
}

currentTab I'm getting from the list of tabs:

tabs: [One, Two, Three]

Solution

  • There are a few ways to force a render. To do so from the parent, set a key on the child. Changing the key will cause the child to rerender:

    HTML:

    <component :is="currentTab" :key="tabKey"></component>
    

    In the parent, define the key as a number:

    data() {
      return {
        tabKey: 0
      }
    }
    

    Change the key:

    methods: {
      resetData() {
        this.tabKey++;
      }
    }
    

    Note: Using this.$forceUpdate from within the component will only cause its view to rerender.