vue3 pinia在App.vue中使用了useStore 报错getActivePinia() was called but there wa no active pinia

事件起因

因为要在全局axios中使用全局的参数,所以要在封装axios方法中使用piniauseStore,因为是axiosjs/ts文件在import时会立即执行,导致组件尚未加载pinia而提前使用了pinia,所以会报错getActivePinia() was called but there wa no active pinia

解决方案

App.vue中使用动态组件,通过判断pinia是否已经创建完成,如果未创建完成则等待pinia创建完成再加载组件。

App.vue文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script setup>
import { defineAsyncComponent, getcurrentInstance } from 'vue'

const index = ref(null)
const app = getcurrentInstance()

const timer = setinterval(() => {
if (app?.appContext.config.globalProperties.$pinia) {
index.value = defineAsyncComponent(() => import('./views/index.vue'))
clearInterval(timer)
}
})

</script>
<template>
<div id="#app" ref="app">
<component :is="index"/>
</div>
</template>