Search code examples
statevuejs3keep-alive

Vue3 force reset/clear of keep-alive components


I'm using keep-alive to maintain the state of a multi-step form in Vue3 so users can navigate back and forth as needed.

What I can't figure out, is how to force a clear of the cache. When users complete the form I give them an option to re-start and I currently clear the form submission object and return the users to page 1 of the form but keep-alive is preserving the form state so checkboxes are pre-selected. Is there a call I can make from my reset function to clear the keep-alive cache? Ideally for only some of the form steps, not all.


Solution

  • I actually ended up using an entirely different method and thought I would put it here in case it is of use to someone else.

    I found it here: https://michaelnthiessen.com/force-re-render/

    Basically, a reset of a component can be forced by changing its key value. This has the added benefit of letting you selectively force a re-render of any number of child components.

    In the parent.

    <PageOne :key="page_one_key">
    
    <script>
    export default {
      ...
      data() {
        return {
          page_one_key: 0,
      }
      },
      ...
      methods: {
       myreset(){
         this.page_one_key += 1;
       }
     }
    }
    </script>
    
    

    If there are downsides to this approach I would love to know but it seems to work perfectly - allows back/forwards navigation of my form and selective resetting of the cached components.

    It is also simple to implement.