npm i vue-i18n
① index.js 示例 =>
import { createI18n } from 'vue-i18n';
import ZH from './zh.js';
import EN from './en.js';
const messages = {
zh: { ...ZH },
en: { ...EN },
};
const i18n = createI18n({
legacy: false,
globalInjection: true,
locale: 'zh',
messages
});
export default i18n;
② zh.js 示例 =>
export default {
person: {
name:'张三',
hobby:'唱跳,rap,篮球'
},
};
③ en.js 示例 =>
export default {
person: {
name:'zhangsan',
hobby:'Singing and dancing, rap, basketball'
},
};
import { createApp } from "vue";
import App from "./App.vue";
import i18n from './i18n/index';
const app = createApp(App);
app
.use(i18n)
.mount("#app");
<template>
<div>
<span> {{ $t("person.name") }} span>
<span> {{ $t("person.hobby") }} span>
div>
template>
<script setup>
import { getCurrentInstance } from "vue";
const { $t } = getCurrentInstance().proxy;
console.log( $t("person.name") ); // => 获取值
script>
<script setup>
import { useI18n } from 'vue-i18n'
const { locale } = useI18n()
// 切换中文
function changeZh(){ locale.value = 'zh'; };
// 切换英文
function changeEn(){ locale.value = 'en'; };
script>