vue3 pinia(报错处理) Did you forget to install pinia?

12,263 阅读1分钟

问题再现

笔者开发vue3 + pinia 项目时,遇到一个很奇怪的报错,pinia.mjs:1699 Uncaught Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?

image.png

意思是并没有引入到pinia,贴上代码:

main.ts

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import ElementPlus from 'element-plus';
import router from '@/router'
import { createPinia } from 'pinia'
const pinia = createPinia()
// import 'element-plus/lib/theme-chalk/index.css';

 // 创建vue实例
 const app = createApp(App);
 // 挂载pinia
 app.use(router);
 app.use(pinia);
 app.use(ElementPlus)
 // 挂载实例
 app.mount('#app');

store/index.ts

import { defineStore } from 'pinia';

 const useUserStore = defineStore("userStore",{
    id: 'user', // id必填,且需要唯一
    state: () => {
        return {
            name: '张三',
            themeColor: "#563493"
        };
    },
    getters: {
        getThemeColor(state) {
          return state.themeColor;
        },
    },
    actions: {
        updateName(name: string) {
            this.name = name;
        },
        updateThemeColor(color: string) {
            this.themeColor = color;
        },
    },
});

export default useUserStore;

引入useUserStore的文件, Nav.vue

<script  lang="ts">
import {
  defineComponent,
  defineAsyncComponent,
  reactive,
} from "vue";
import  useUserStore  from '@/store'
const userStore = useUserStore();

export default defineComponent({
  name: "Nav",
  components: {
    
  },
  computed: {
    
  },
  watch: {
    
  },
  mounted() {
  },
  setup(props, context) {
    const state = reactive({
      visible: false,
    });
    return {
      state,
    };
  },
});


</script>

解决方案、

原来,pinia需要在vue3的setup里面声明,如果直接引用,这个时候pinia并没有加载完成,修改Nav.vue文件,将const userStore = useUserStore()放入setup里。

<script  lang="ts">
import {
  defineComponent,
  defineAsyncComponent,
  reactive,
} from "vue";
import  useUserStore  from '@/store'

export default defineComponent({
  name: "Nav",
  components: {
    
  },
  computed: {
    
  },
  watch: {
    
  },
  mounted() {
  },
  setup(props, context) {
    const userStore = useUserStore();
    const state = reactive({
      visible: false,
    });
    return {
      state,
    };
  },
});


</script>

就解决问题了

image.png