Vue Js 3未保留Pinia全局状态

huangapple go评论65阅读模式
英文:

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">

huangapple
  • 本文由 发表于 2023年6月14日 23:32:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定