在vue中使用Pinia时报错:
getActivePinia was called with no active Pinia. Did you forget to install pinia?
报错原因:
pinia在main.js中还未注册好,便在其他文件中使用了它。
解决方法:
- 创建 src/store/index.js文件
import { createPinia } from 'pinia';
const pinia = createPinia();
export default pinia;
- src/store/useStore.js文件
import { defineStore } from 'pinia'
const useWebsiteStore = defineStore('websiteStore', {
state() {
return {
websites: []
}
},
actions: {
add(item) {
console.log(item)
}
}
})
export default useWebsiteStore
- main.js中注册pinia
import { createApp } from 'vue';
import App from './App.vue';
import pinia from './stores';
createApp(App).use(pinia).mount('#app');
- 在其他文件中使用pinia
import pinia from '../store/index'
import useWebsiteStore from '../store/websiteStore.js'
const websiteStore = useWebsiteStore(pinia)
websiteStore.add('item')