【Vite+Ts+Vue3+Pinia】使用i18n国际化简单配置

安装i18n

cnpm install vue-i18n --save

src目录新建language文件夹并新建以下文件

新建en.ts(英文)

const messages = {
  home: {
    title: "Book Store",
    hint: "Computer Science And Software Engineering",
    guessYouLike: "Guess You Like",
  },
};
export default messages;

新建zh.ts(中文)

const messages = {
  home: {
    title: "1111",
    hint: "计算机",
    guessYouLike: "喜欢",
  },
};
export default messages;

其他的语言自行新建即可

新建i18n.ts

import { createI18n } from "vue-i18n";

// 引入上面新建的语言文件
import en from "./en";
import zhTW from "./zhTW";

const i18n = createI18n({
  legacy: false,
  locale: localStorage.getItem("language") || "zhTW",
  fallbackWarn: false,
  missingWarn: false,
  warnHtmlMessage: false,
  messages: {
    // zh,
    en,
    zhTW,
  },
});
export default i18n;

安装Pinia

cnpm install pinia --save

配置main.ts

import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";

import i18n from "./language/i18n";

import { createPinia } from "pinia";
const app = createApp(App);
app.use(i18n).mount("#app");

src目录新建store文件夹》新建index.ts

import { defineStore } from "pinia";
import i18n from "../language/i18n";

export const useCounterStore = defineStore("counter", {
  state: () => ({
    lang: localStorage.getItem("language") || "zhTW",
  }),
  actions: {
    // 设置语言
    setLanguage(data: any) {
      i18n.global.locale = data;
      localStorage.setItem("language", data);
      this.lang = data;
    },
  },
});

页面使用

import { useCounterStore } from "@/store/index";

const store = useCounterStore();
store.setLanguage('en');

// 读取:
store.lang

// template语言:
{{$t("home.title")}}

踩坑:切换后语言没更新,必须手动刷新 解决:

切换语言的文件方法引入:
import type { ComponentInternalInstance } from "vue";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

(proxy as any).$i18n.locale = index; // 切换当前语言

你可能感兴趣的:(Vue.js,前端,前端收徒,vue.js,javascript,前端)