当前位置: 首页 > news >正文

vue3.0 + vue-i18n:使用方法和自动引入多个语言文件

1、下载依赖

npm install vue-i18n --save

2、看文件结构:
在这里插入图片描述
en、zh 中 index.ts 作用就是自动引入 文本文件,因为 vue3.0不支持 require,所以我们用 import 替换,方法如下:

// 批量引入英文文件
const modulesFilesEn:any = import.meta.glob("./*.js",{ eager: true })
const modulesEn:any = {};
for (const path in modulesFilesEn) {const moduleName: any = path.replace(/(.*\/)*([^.]+).*/gi, "$2")modulesEn[moduleName] = modulesFilesEn[path].default
}
export default modulesEn
// 批量引入中文
const modulesFilesZhCN:any = import.meta.glob("./*.js",{ eager: true })
const modulesZhCN:any = {};
for (const path in modulesFilesZhCN) {const moduleName = path.replace(/(.*\/)*([^.]+).*/gi, "$2")modulesZhCN[moduleName] = modulesFilesZhCN[path].default;
}
export default modulesZhCN

最终在 index.ts 中

import { createI18n } from 'vue-i18n';
import zh from './zh'
import en from './en'
import settings from '../settings'
const i18n = createI18n({locale: 'zh_CN', // 本地持久化时的 localStorage key  英文-en// fallbackLocale: 'zh_CN', //没有英文的时候默认中文语言messages: {zh_CN: zh,	//引入语言文件en: en}
})
export default i18n

main.ts中

import i18n from './i18n/index'
app.use(i18n)

文件中使用

<span class="title">{{ $t('component.title') }}</span>

或者

<span class="title">{{ t('component.title') }}</span>import { useI18n } from 'vue-i18n';
const { t } = useI18n();

require用法

const en = {}
// 当前目录下所有 js 文件
const ctx = require.context('./', true, /.js$/)
ctx.keys().forEach(file => (en[file.replace(/^\.\/(\w+)\.js$/, '$1')] = ctx(file).default))
export default en

http://www.mrgr.cn/news/50787.html

相关文章:

  • Vulhub DerpNStink: 1靶机详解
  • MySQL索引、事物与存储引擎
  • (二)Python输入输出函数
  • MATLAB(Octave)混电动力能耗评估
  • 2024年四非边缘鼠鼠计算机保研回忆(记录版 碎碎念)
  • Redis技术指南:数据类型、事务处理与过期键管理
  • VRP_用MDP建模_20241015
  • [Linux] 创建可以免密登录的SFTP用户
  • Pyenv 介绍和安装指南 - Ubuntu 24
  • opencv学习:人脸识别器特征提取BPHFaceRecognizer_create算法的使用
  • unity学习-Directional light光的设置
  • 爬虫之数据解析
  • 详解腐烂的苹果(图+代码+广度优先遍历)
  • 快捷支付的优势和特点
  • 中心极限定理的Python实践
  • 【p2p、分布式,区块链笔记 UPNP】: 简单服务发现协议 SSDP
  • 『大模型笔记』pip3 install -e .[stable]作用!
  • 【Linux】基础IO
  • 获取上海证券交易所和深圳证券交易所上市公司的实时股票数据
  • 三本非OA顶级快刊,IEEE Trans“灌水神刊”4个月录用!领域内佼佼者,你选谁?