【pinia】router使用pinia报错 getActivePinia was called with no active Pinia. Did you forget to install

问题

使用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为响应式的
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值