Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain state between Vue pages

I'm working on a form in VueJS and want the user to be able to confirm the contents before submission.

This involves routing from form page -> confirm page.

However, when I have the user go back the state of the previous page is reset.

Is there a way I can cleanly preserve the state of the previous page without digging far into the store's state?

Or is this approach against the principles of Vue?

Previous approach tried is to save the form's state when moving to the confirm screen.

Then when moving back the previous state is restored by checking if the data exists on create, e.g.

onCreated() {
  this.myFormData = this.$store.state.[myFormModuleName].formData ? this.$store.state.[myFormModuleName].formData : setSomeDefaultInstead();
}

And while this works it feels hacky and is difficult to test.

This may need editing for being too broad, but is there a 'best practice' approach between Vue for maintaining state between pages as you can do in Angular? Or are plugins the only way to go?

As mentioned above, I would like to ensure that the approach used doesn't break pre-existing tests for the form.

like image 604
peanut Avatar asked Oct 25 '25 05:10

peanut


1 Answers

Without having the entire code available, I think you best bet might be a <keep-alive> component around your router-view, have a look at the section in the docs here: https://v2.vuejs.org/v2/api/#keep-alive

This should preserve the entire local state of your component when it's being used again.

like image 158
Tobias G. Avatar answered Oct 26 '25 19:10

Tobias G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!