vue3 在setup 外部调用 useStore() 为 undefined 解决

900 阅读1分钟

vue3 在setup 外部调用 useStore() 为 undefined 解决

问题使用场景,在vue3项目中打包组件库之后,在另一个vue3项目中使用,发现打包出的组件中vuex获取为undefiend。在本地项目中使用不报错

import { useStore } from "vuex";

setup() {
    const store = useStore();
    
    const getData = computed(() => { return store.getters.userInfo });
    
    return {
        getData
    }
}

// 如果这样写在,打包成组件库之后,使用该组件时会报错 undefiend

经过查询资料(更多的是问度娘...),这样使用组件属于外部使用 useStore,因为使用 useStore() 的主要目的是引入 store

  • 外部使用则 直接不使用 useStore(), 因为使用 useStore() 的主要目的是引入 store;那么外部可以直接 如main.ts 一样引入store;
import { useStore } from "vuex";
import _store from "@/store";

setup() {
    const store = useStore() || _store;
    
    const getData = computed(() => { return store.getters.userInfo });
    
    return {
        getData
    }
}