vue3 + i18n
安装:
npm install vue-i18n
yarn add vue-i18n
main.js
如果在一个模块系统中使用它,你必须通过 Vue.use() 明确地安装 vue-i18n:
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './router/index'
import i18n from './lang/i18n'
const app = createApp(App)
app.use(ElementPlus)
app.use(router)
app.use(i18n)
app.mount('#app')
在src目录下创建lang文件夹,下包含ch.js(中文包) en.js(英文包) index.js i18n.js(配置i18n)
cn.js
export default{
message: {
username: '用户名',
password: '密码',
login: '登录',
captcha: '验证码',
forgetPassword: '忘记密码?',
loginTip: '当前登录结果随机。验证码随便填',
editpassword: '修改密码',
logout: '退出登录',
errMsg: {
inputRequired: '请输入{cont}',
selectRequired: '请选择{cont}'
}
},
}
en.js
export default{
message: {
username: 'User Name',
password: 'Password',
login: 'Login',
captcha: 'Captcha',
forgetPassword: 'Forget Password?',
loginTip: 'The login result is random. Just fill in the captcha',
editpassword: 'Edit Password',
logout: 'Logout',
errMsg: {
inputRequired: 'Please Input {cont}',
selectRequired: 'Please Select {cont}'
}
},
}
index.js
import cn from './cn'
import en from './en'
export default { cn, en };
i18n.js
import { createI18n } from 'vue-i18n' //引入vue-i18n组件
import messages from './index'
const i18n = createI18n({
fallbackLocale: 'cn',//找不到字段会以此语言展示
globalInjection:true,
legacy: false, // you must specify 'legacy: false' option
locale: language.split("-")[0] || "cn",//默认显示的语言
messages,//本地化的语言环境信息。
});
export default i18n
使用
<div>{{ $t(`message.login`) }}</div>
在setup中使用
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
console.log(t('login.useName'))
</script>
切换语言
<template>
<div class="menu">
<div @click="changeLang('en')">English</div>
<div @click="changeLang('zh')">中文</div>
</div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { locale } = useI18n()
const changeLang = (lang: string) => {
locale.value = lang
localStorage.setItem('lang', lang)
}
</script>
标签:vue,cn,app,js,vue3,i18n,import
From: https://www.cnblogs.com/Dasate/p/17491678.html