头图

原因:
在组件外使用pinia了,所以导致没有正确缓存
image.png
如果正确缓存,控制台会打印store安装完毕的提示
我在项目使用了i18n,导致在router.beforeEach之前使用pinia了(服务端使用),也就是官网所说的,组件外使用pinia
具体代码如下:

// i18n.ts
import { createI18n } from "vue-i18n";
import zhCN from "@/lang/modules/zhCN";
import enUS from "@/lang/modules/enUS";

// 在组件外使用了pinia
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "@/store/modules/theme-config";
const themeStore = useThemeConfig(pinia);
const { language } = storeToRefs(themeStore);

/* 这里必须是messages名称 */
const messages = {
  "zh-CN": zhCN,
  "en-US": enUS
};

const i18n = createI18n({
  legacy: false, // Composition API模式需要设为false
  globalInjection: true, // 全局生效: $
  locale: language.value, // 默认语言
  messages // 数据源
});

export default i18n;

解决:
如果组件外不使用pinia,store就可以被缓存

import { createI18n } from "vue-i18n";
import zhCN from "@/lang/modules/zhCN";
import enUS from "@/lang/modules/enUS";

/* 获取语言-直接从本地获取,为使用pinia */
const getLang = () => {
  let store = localStorage.getItem("theme-config");
  if (store) {
    return JSON.parse(store)?.language || "zh-CN";
  } else {
    return "zh-CN";
  }
};
/* 这里必须是messages名称 */
const messages = {
  "zh-CN": zhCN,
  "en-US": enUS
};

const i18n = createI18n({
  legacy: false, // Composition API模式需要设为false
  globalInjection: true, // 全局生效: $
  locale: getLang(), // 默认语言
  messages // 数据源
});

export default i18n;

image.png
image.png


参考资料:
组件外使用store


兔子先森
388 声望16 粉丝

致力于新技术的推广与优秀技术的普及。