安装
npm install vue-i18n@9 -S || yarnadd vue-i18n@9
src目录下新建lang文件夹
在lang文件夹下新建index.js、zh.js、en.js
zh.js
module.exports = {
name:'中文简体',
}
en.js
module.exports = {
name:'English',
}
index.js
import En from '../lang/en' // 英语语言包
import Zh from '../lang/zh' // 中文语言包
const messages = {
'en-US': {...En },
'zh-HK': {...Tc },
}
//键名为需要给后端传的参数名
// 使用
// <div class=""> {{ $t('msg.test') }}</div>
//1.组件的模板中使用 $t()
//2.组件的js使用 i18n.t
//3.非组件中使用i18n.global.t
//4.切换组件还是要
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
// 使用 Composition API 模式,则需要将其设置为false
legacy: false,
// 全局注入 $t 函数
globalInjection: true,
locale:sessionStorage.getItem('lange') || 'zh-HK',
messages,
// 防止使用v-html=“$t(“”)”的xss警告
warnHtmlMessage: false
})
export default i18n
main.js
import { createApp } from 'vue'
import App from './App.vue'
import i18n from './utils/i18n.js'
createApp(App)
.use(i18n)
.mount('#app')
使用
<template>
<button type="button" @click="changeLang('zh')">点击切换中文</button>
<button type="button" @click="changeLang('en')">点击切换英文</button>
<h2>{{ $t("title") }}</h2>
<h2>{{ title }}</h2>
</template>
<script setup>
import { ref, computed , getCurrentInstance} from "vue";
import { useI18n } from "vue-i18n";
const { locale} = useI18n(); //当前语言
const { $t } = getCurrentInstance().proxy;
const changeLang = (value: string) => {
locale.value = value;
};
// 使用计算属性实现响应式
const title = computed(() => $t("title"));
const changeLang = (value: string) => {
locale.value = value;
};
</script>
<style scoped>
</style>