博客列表 >uniapp中使用pinia管理状态

uniapp中使用pinia管理状态

浅浅的无名小卒
浅浅的无名小卒原创
2022年03月24日 16:34:316748浏览

安装pinia官方文档和uniapp vue3版本,main.js文件如下:

  1. import { createPinia } from 'pinia'
  2. import { createSSRApp } from 'vue'
  3. import App from './App.vue'
  4. export function createApp() {
  5. const app = createSSRApp(App)
  6. const pinia = createPinia();
  7. app.use(pinia)
  8. return {
  9. app
  10. }
  11. }

结果编译成功,运行报错:
报错

  1. 13:33:26.965 reportJSException >>>> exception function:createInstanceContext, exception:white screen cause create instanceContext failed,check js stack ->Uncaught Error: [?]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
  2. 13:33:27.028 const pinia = createPinia()
  3. 13:33:27.068 app.use(pinia)
  4. 13:33:27.120 This will fail in production.

一头雾水,明明已经安装了,为什么提示没有安装呢?

网上搜了一圈,uniapp 与 pinia 两个关键字关联的结果少之又少,最终尝试从源码中找寻答案。

从unaipp官方文档中得知,vue3版本使用ssr模式创建应用,渲染速度更快。
所以,在使用pinia上,也应该注意,使用相应的规范。
在Server-Side Rendering (SSR)章节中,是这么写的:
Creating stores with Pinia should work out of the box for SSR as long as you call your useStore() functions at the top of setup functions, getters and actions:

  1. export default defineComponent({
  2. setup() {
  3. // this works because pinia knows what application is running inside of
  4. // `setup()`
  5. const main = useMainStore()
  6. return { main }
  7. },
  8. })

If you need to use the store somewhere else, you need to pass the pinia instance that was passed to the app to the useStore() function call:

  1. const pinia = createPinia()
  2. const app = createApp(App)
  3. app.use(router)
  4. app.use(pinia)
  5. router.beforeEach((to) => {
  6. // ✅ This will work make sure the correct store is used for the
  7. // current running app
  8. const main = useMainStore(pinia)
  9. if (to.meta.requiresAuth && !main.isLoggedIn) return '/login'
  10. })

按照我的理解就是,在setup函数中直接使用useStore函数是没有问题的,因为setup的生命周期之前就已经完成了pinia的初始化了,但是,如果你要在setup函数之外使用pinia,这就需要自己手动创建pinia对象。但是检查一番后,发现并不是这个问题。

最后实在没办法,回滚到上一个没使用pinia的版本,然后再一步步往下走,发现是有个页面中在data()函数之前就使用了useStore方法,报错的意思就是说pinia初始化还没完成,就开始使用了。不得不说,uniapp的错误提示还真是少的可怜,完全摸不到边,之后还是要学聪明点,写一步,调试一步。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议