博主信息
博文 3
粉丝 0
评论 0
访问量 11458
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
uniapp中使用pinia管理状态
浅浅的无名小卒
原创
7859人浏览过

安装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举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学