cnpm install vue-i18n --save
新建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;
cnpm install pinia --save
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");
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; // 切换当前语言