Vue3はi18nプラグインを利用して多言語切り替え機能を実現しています

1. i18n プラグインをダウンロードする

npm install vue-i18n  或者 yarn add vue-i18n

2. 翻訳ファイルのテキストコンテンツを作成し、index.js と i18n.ts を作成します

Index.ts は、スコープ ファイルの内容のエクスポート ファイルです。
i18n.ts は、翻訳ファイルのエントリ ファイルです。このファイルは、グローバル main.ts ファイルにインポートする必要があります
(ts または js は、独自のプロジェクトの文法に依存します)。
以下の 3 つのファイルの内容です。

インデックス.ts

import ch from './zh-CN'


import en from './en'

export default {
    
    
  ch, en
}

i18n.ts

//进行切换语言环境的时候,我们可以使用前端缓存来存储,判断当前的语种环境
import {
    
     createI18n } from 'vue-i18n' //引入vue-i18n组件
import messages from './index'

const i18n = createI18n({
    
    
  fallbackLocale: localStorage.getItem('lang') || "en",//预设语言环境
  globalInjection: true,
  legacy: false, // you must specify 'legacy: false' option
  locale: localStorage.getItem('lang') || "en",//默认显示的语言 
  messages,//本地化的语言环境信息。
});

export default i18n;

zh.ts en.ts

const en = {
    
    
  messages: {
    
    
  	"example": "example",
  	}
  }
export default en;
const zhCN = {
    
    
  messages: {
    
    
  	"example": "示例",
  	}
  }
export default zhCN;

main.ts

//ts还是js,具体要看项目语法进行引入
import i18n from './lang/i18n';

app.use(i18n);
app.mount('#app');

3. 翻訳テンプレートの構文を使用する

お寺で使われている

 <span>{
    
    {
    
     $t("messages.upload") }}</span>  //需带{
    
    {}}
 <span :label="$t("messages.upload")"></span>//正常属性写法
 <span>{
    
    {
    
     state.name }}</span>
 <script setup>
 import {
    
     reactive } from 'vue';
  	import {
    
     useI18n } from "vue-i18n";
	const {
    
     locale } = useI18n();
	let state =reactive( {
    
    
		name:t('messages.upload')
	})
 </script>

ルーティングで使用され、タイトルを変更します

import i18n from '@/lang/i18n.ts'
const t = i18n.global.t;


export const conRoutes = [
{
    
    
  path: '/example',
  title: t('messages.example'),
}
]

おすすめ

転載: blog.csdn.net/m54584mnkj/article/details/131475092