在现代前端开发中,会遇到国际化的需求,就是配置多种语言,这时候就用到了i18n插件下面展示插件如何使用:
下载插件
pnpm install vue-i18n
配置插件
创建文件夹和对应的ts文件
en.ts
//en.ts
const en: any = {
首页: 'Home',
管理: 'Management',
设置: 'Setting',
退出: 'Logout',
翻译: 'Translate',
测试项目: 'Test project',
}
export default en
zh.ts
//zh.ts
const zh: any = {
首页: '首页',
管理: '管理',
设置: '设置',
退出: '退出',
翻译: '翻译',
测试项目: '测试项目',
}
export default zh
index.ts
//index.ts
import { createI18n, I18n } from 'vue-i18n'
import en from './en'
import zh from './zh'
const message = {
zh: zh,
en: en,
}
const i18n: I18n = createI18n({
locale: 'zh', // 设置语言类型
legacy: false, // 如果要支持compositionAPI,此项必须设置为false;
globalInjection: true, // 全局注册$t方法
messages: message,
})
export default i18n
在main.ts中全局配置
import { createApp } from 'vue'
import i18n from './i18n'
const app = createApp(App)
app.use(i18n).mount('#app')
在模板中使用
在template
模板中使用,这个比较简单,直接使用全局方法$t
即可
在script
中,我们需要引入vue-i18n
的useI18n
方法,并需要将 t 方法解构出来
<template>
<n-button>{{ $t('首页') }}</n-button>
<n-button>{{ $t('管理') }}</n-button>
<n-button>{{ $t('设置') }}</n-button>
<n-button>{{ $t('退出') }}</n-button>
<n-button>{{ text }}</n-button>
</template>
<script setup lang="ts">
import { h } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 解构出t方法
const text = t('翻译')
</script>
<style lang="sass" scoped></style>
局部截屏(有效区域) ,现在是中文模式,
当把 i18n/index.ts中的 locale: 'zh'改为 locale: 'en', 可以看到语言切换成功
在ts文件中使用
这是一个路由守卫的配置文件,主要是说一下 i18n 在ts文件中的使用方法,在ts
文件中,通过i18n.global.t方
法来使用,下面的例子是在给网页标题设置
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import config from '@/config/index'
import i18n from '@/i18n'
nprogress.configure({ showSpinner: false })
router.beforeEach((to: any, from: any, next: any) => {
// document.title = `${config.setting.title} - ${to.meta.title}`
document.title = `${i18n.global.t(config.setting.title)} - ${i18n.global.t(to.meta.title)}`
nprogress.start()
next()
})
//全局后置守卫
router.afterEach((to: any, from: any) => {
nprogress.done()
})
效果:
热情提示
如果遇到 ,在el-dropdown-menu 和 el-dialog 等一些组件中无法使用的情况,可能是因为作用于的问题或者组件渲染时机的问题。可以创建方法在标签语句中通过调用方法传值的方式实现。