vue 您所在的位置:网站首页 locale中文翻译 vue

vue

2024-05-27 08:28| 来源: 网络整理| 查看: 265

目录

安装引入 

使用

vue3需安装9.x版本的vue-i18n,官方文档目前没有中文版

官方文档: Vue I18n

安装引入 

第一步:安装vue-i18n

// npm npm install vue-i18n@9 // yarn yarn add vue-i18n@9

第二步: 为了方便统一管理以及后期需在router.js等地方获取当前的语言,

                在utils下新建lang文件夹,

                在lang文件夹下分别建index.js、en.js、zh.js文件

第三步: 在index.js里,引入vue-i18n,并进行相关配置后导出

index.js

我是将语言记录在localStorage里,所以首次要先去localStorage里取值,没有的话默认是中文

import { createI18n } from 'vue-i18n' import en from './en' //英文 import zh from './zh' //中文 const i18n = createI18n({ legacy: false, // 使用CompotitionAPI必须添加这条. locale: localStorage('lang') || 'zh', // set locale设置默认值 fallbackLocale: 'zh', // set fallback locale messages: { en, zh, // set locale messages }, }) export default i18n

 第四步:在main.js里,将vue-i18n注入全局

import { createApp } from 'vue' import App from './App.vue' import router from './router' import { store } from './store' import ElementPlus from 'element-plus' import i18n from '@/utils/lang' const app = createApp(App) app.use(store) app.use(router) app.use(ElementPlus) // 全局注入语言 app.use(i18n) app.mount('#app')

第五步:设置自动导入,前提是安装了自动导入插件unplugin-auto-import

vite.config.js

import { defineConfig } from 'vite' import AutoImport from 'unplugin-auto-import/vite' export default ({ mode }) => { return defineConfig({ plugins: [ AutoImport({ imports: [ 'vue-i18n', ], dts: './auto-imports.d.ts', eslintrc: { enabled: false, // 配置更新时临时设为true, }, }), ], resolve: { alias: { 'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js', }, }, }) }

 

到此,vue-i18n就引入成功啦。

使用

1、在zh.js及en.js里添加相应的中英文

2、在组件模板里使用 

//基本用法 {{ $t('common.title') }} //传值用法 {{ $t('common.title2',{date:'2023'}) }} //zh.js //title2:'今年是{date}' //en.js //title2:'This year is {date}'

3、在setup里使用,以及进行语言切换

t:即组件里使用的$t

local:当下语言

const { t, locale } = useI18n() const title = ref('测试') title.value = t('common.title') // 切换语言 function toggleLang() { locale.value = locale.value === 'zh' ? 'en' : 'zh' localStorage.set('lang', locale.value) }

4、在其他js文件里使用,如:router.js 

import { createRouter, createWebHistory } from 'vue-router' import i18n from '@/utils/lang' export const routes = [ { path: '/home', name: 'home', component: () => import('@/views/home.vue'), }, ] const router = createRouter({ history: createWebHistory('/web/'), routes, }) router.afterEach((to, form, failure) => { if (!failure) { // 更改标签页标题 const { t } = i18n.global document.title = t(`menu.${to.name}`) || 'page' } })  element-plus

在app.vue中引入element多语言

如果是dialog或者popover这种在app.vue之外的,里面有用到element组件的,可将内容用el-config-provider再包裹一遍

import zhCn from 'element-plus/lib/locale/lang/zh-cn' import en from 'element-plus/dist/locale/en.mjs' const { locale } = useI18n()


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有