Home > front end >  Vue.js: How to keep data of a child-component when changing route and view the best way?
Vue.js: How to keep data of a child-component when changing route and view the best way?

Time:07-06

I am currently trying to develop a web shop that has a total of 6 parent views.

Almost every parent view also has the child component "shopping cart" - an overview of the products currently in the shopping cart. This component is always displayed on the right side of the respective view and its content should (obviously) be retained beyond the route change.

Now I somehow had a little hope (no idea why) that Vue.js would simply recognize that the same child component was also used in the next view and the data would therefore simply be retained - wrong thought :').

So it looks like I'll have to re-implement (or rather copy-paste) the data and logic over and over again in each view and existing information like

- Total price

- Products in the shopping cart

- Quantities

etc. from one view to the next over and over again.

In principle, this problem could be solved relatively easily by defining the entire logic not within the parent component, but in the shopping cart component itself. However, someone once said to me that good programming style is characterized by keeping the child components "dumb" and keeping the logic within the Parent components.

For this reason I hope you can tell me how I can solve this problem in the most efficient way to move the existing information of the child component from one parent-view to another and to be able to implement the logic of the shopping cart in the most efficient way.

Thanks in advance!

CodePudding user response:

We can use a state management tool for saving states, but if you want them to persist as if you got other page and make a "back" button click, you can try to use "pinia" with the "persist" option. you can find a lot of reference.

  • Related