英文:
Vue Js 3 not keeping Pinia global state
问题
我正在一个小型在线商店项目上工作。我正在使用Pinia将我获取的数据保存为产品和其他内容的数组。现在,我不知道为什么状态无法保持一致。我正在使用路由和组件来创建不同的页面。在主页上,您可以选择一个产品并查看其页面,然后将产品添加到购物车中。访问购物车页面,它会显示产品。如果您回到前一页,购物车仍然会保留该产品。但是,如果您返回两页(回到主页),购物车列表将变为空。这仅在浏览主页和购物车时才会发生。只有在访问产品页面或回退到第一个页面时才会发生。我尝试在网上搜索解决方案,但没有找到任何信息。这是仓库链接,如果您能检查一下... https://github.com/leorob88/kreas/tree/main/src
英文:
I'm working on a project as a little online store. I'm using Pinia to keep the data i'm fetching as an array for the products and other things. Now, I don't know why but the state doesn't keep up. I'm using routing and components to have different pages. In the home you can choose a product and view its page, then you can add the product to your cart. Visiting the cart page, it shows the product. If you go on previous page, the cart still keeps the product. Instead, if you back 2 pages (the home) the cart list becomes empty. This is not the case when browsing through home and cart. It only happens when visiting a product page or going back until the first page. I tried searching for solutions online but found nothing. This is the repo, if you can check... https://github.com/leorob88/kreas/tree/main/src
答案1
得分: 2
你的问题的根本原因是在代码中使用了<a>
标签来在产品页面和详情页面之间进行导航。你应该改用<router-link>
标签。本地锚标签会导致页面完全重新加载,从而导致状态丢失。当vue-router控制导航时,组件会在无需重新加载页面的情况下进行响应式切换,并保持存储状态。
英文:
The root cause of your issue is the use of <a>
tags in your code to navigate between the Product page and the Details page. You should use <router-link>
tags instead. The native anchor tags cause navigations to completely reload the page, which results in loss of state. When vue-router controls the navigation the components reactively switch without having to reload the page and maintains the state of your store.
<a :href="['/details/' + props.id]">
should be
<router-link :to="'/details/' + props.id">
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论