如何在NPM软件包内使用PINIA?
I have similar issue as mentioned here, but with Pinia in my case. It's much harder to get Pinia to work outside of Vue components, because of "Uncaught Error: [????]: getActivePinia was called with no active Pinia. Did you forget to install pinia?"
, but in this case it is even harder.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是最干净的解决方案,因为它需要在将使用您的包的项目中安装并初始化 Pinia,但如果您这样做是为了内部使用,那完全没问题。
所以,在我的包中,它看起来像这样:
在其他项目中:
我注意到在 SPA 模式下,您可能不需要为您的包提供活动 pinia,它可以自行解决,您只需要确保
app.use(pinia)
在初始化包之前。但这在 Nuxt SSR 模式下不起作用,所以是的,需要这种解决方法:(我认为我们应该在 Pinia 的存储库中提出这个问题。我不明白为什么它必须以这种方式工作。您需要在setup() 对于应用程序来说非常频繁,有时甚至至关重要,因此它应该更容易
PS
另外,请记住存储名称冲突的可能性在整个应用程序
P.PS
SSR 解决方案中应该是唯一的:
插件/MyPackage.plugin.js:
Not the cleanest solution, because it requires to have Pinia installed and initialized in the project where your package will be used, but if you're doing this for internal use it is totally okay.
So, in my package it looks like this:
And in other project:
I noticed that in SPA mode you may not need to provide active pinia to your package, it could figure it out itself, you just need to make sure to
app.use(pinia)
before you initialize you package. But this doesn't work in Nuxt SSR mode, so yeah, this workaround required :(I think we should raise this question in Pinia's repository. I don't see why it have to work this way. Cases where you need stores outside of setup() are so often and even crucial sometimes for applications, so it should be much easier.
P.S.
Also, keep in mind the possibility of store names collisions. Names should be unique across entire application
P.P.S.
SSR solution:
plugins/MyPackage.plugin.js:
对于任何偶然发现这个问题的人这可能是一个有用的来源。它使用 Vite 进行捆绑。
For anyone stumbling upon this problem this might be a helpful source. It uses Vite for bundling.