vue3/pinia:将主存储添加到每个组件:mainstore()还是提供/注入?

发布于 2025-01-24 09:30:38 字数 215 浏览 0 评论 0原文

将PINIA存储添加到VUE3组件的默认方法是通过在每个VUE3组件中加载namestore.js

import {nameStore} from "@stores/nameStore.js"
const nameStr = nameStore()

几乎所有主要组件中使用的主要PINIA商店的方法都更好? (但在小部分中使用不多)

Default way to add a pinia store to Vue3 component is through loading nameStore.js in each Vue3 component

import {nameStore} from "@stores/nameStore.js"
const nameStr = nameStore()

Vue3 has it's own Provide/Inject.

Which approach is better for the main pinia store that's used in almost all major components? (but not much used in small components)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丢了幸福的猪 2025-01-31 09:30:38

在功能上,您的两个选项之间没有不同的不同,如@duannx所述。归结为偏好。

使用提供/注入时,请避免导入语句和函数调用,将样板还原为单行const namestore = inmext('namestore'),这些缺点是带有supply/supply/suppory/suffor/注入:

  • 它导致组件之间的紧密耦合,使它们在其他情况下不可用。但是,如果您将商店注入应用程序的根部组件,这并不重要。
  • 没有编译时安全性:如果未正确提供商店,您的注入呼叫将返回undefined,只能在运行时找到。

IMO导入和调用商店挂钩的“正常”方式没有类似的问题,因此我通常建议使用它而不是提供/注入,这增加了(再次是IMO)不必要的复杂性。但是正如我所说,最终这是一个品味问题:)

Functionally there is no differece between your two options, as already stated by @Duannx. It comes down to preferences.

When using provide/inject you avoid the import statement and the function call, reducing the boilerplate to a single line const nameStore = inject('nameStore'), the drawbacks are the usual ones that come with provide/inject:

  • It leads to tight coupling between your components, making them less reusable in other contexts. However, if you inject your store at the root component of your app, this won't matter much.
  • There is no compile-time safety: If the store was not provided correctly, your inject call will return undefined, which will only be found out during runtime.

IMO the "normal" way of importing and calling the store hook has no similar problems, so I would generally suggest to use it rather than provide/inject, which adds (again, IMO) unnecessary complexity. But as I said, ultimately it's a matter of taste :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文