vue3 封装组件中使用 pinia 报错

发布时间 2023-04-10 15:55:22作者: optre

报错信息:

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:1692

image
提示说,我没有注册pinia,其实我已经在main.ts中引入了

import { createApp } from 'vue'
import { createPinia } from 'pinia'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)

报错原因:

定义组件使用的是defineComponent, 在引入使用store时,放在了setup外,大致结构如下

import { defineComponent } from 'vue'
import { useAppStore } from '@/store/modules/app'

const appStore = useAppStore()
const TableIcon = computed(() => appStore.getTableIcon)

export default defineComponent({
	name: 'Table',
	setup(){
	 
	}
})

调整 useAppStore 使用位置, 组件报错解决

import { defineComponent } from 'vue'
import { useAppStore } from '@/store/modules/app'

export default defineComponent({
	name: 'Table',
	setup(){
	 const appStore = useAppStore()
	 const TableIcon = computed(() => appStore.getTableIcon)
	}
})