Vue3 uses i18n plug-in to realize the function of switching between multiple languages

1. Download the i18n plugin

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

2. Create the text content of the translation file, create index.js and i18n.ts

index.ts is the export file of the scope file content.
i18n.ts is the entry file of the translation file. This file needs to be imported into the global main.ts file
(ts or js depends on the grammar of its own project).
The following are the contents of the three files

index.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. Use the syntax of the translation template

used in temple

 <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>

Used in routing, change title

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


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

Guess you like

Origin blog.csdn.net/m54584mnkj/article/details/131475092