问题

使用pinia出现以下报错:

app.js:204 Uncaught Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
	const pinia = createPinia()
	app.use(pinia)
This will fail in production.
    at useStore (pinia.mjs?b318:1696:1)
    at eval (index.js?5aa4:9:1)
    at ./src/router/index.js (app.js:52:1)
    at __webpack_require__ (app.js:201:33)
    at fn (app.js:457:21)
    at eval (main.js:5:71)
    at ./src/main.js (app.js:41:1)
    at __webpack_require__ (app.js:201:33)
    at app.js:1382:109
    at __webpack_require__.O (app.js:247:23)

案例

main.js文件:

import { createApp } from 'vue'
import App from './App.vue'
import pinia from '@/store/index'
import router from './router/index'

const app=createApp(App)
app.use(pinia)
app.use(router);
app.mount('#app')

store/index.js文件:

import { createPinia } from "pinia";
const pinia=createPinia()
export default pinia;

store/store.js文件:

import { defineStore } from 'pinia'
export const main = defineStore('main', {
  state: () => {
    return {
      count: 0,
      name:'123'
    }
  }, 
  actions: {
    increment(){
      this.count++
    }
  },
  getters:{
    getCount: (state) => state.count,
  }
})

router/index.js文件:

import {createRouter,createWebHistory} from 'vue-router'

import { main } from '@/store/store'
let store=main() 	// 这里报错

const routes=[
  {
   ...
  }
]
const router=createRouter({
  routes,
  history:createWebHistory(process.env.BASE_URL)
})

export default router

解决方法

分析原因:因为在mian.js中,注册router总比pinia先,所以不能使用到store/index.js文件中createPinia方法,只能在router文件中再createPinia一次,才能使用到pinia。

正确引用:
把router/index.js文件中的以下代码

import { main } from '@/store/store'
let store=main() 	// 这里报错

改为:

import pinia from '@/store/index'  // createPinia()
import { main } from '@/store/store'
import {storeToRefs} from 'pinia'
let store =main(pinia)
let {count}=storeToRefs(store)  // 此时count为响应式的
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐