vue 多语言 vue-i18n
https://github.com/kazupon/vue-i18n github地址
1.
npm install vue-i18n
2.main.js中
import VueI18n from 'vue-i18n'
3.加入一个变量 main修改
const numberFormats = { 'en-US': { currency: { style: 'currency', currency: 'USD' } }, 'ja-JP': { currency: { style: 'currency', currency: 'JPY', currencyDisplay: 'symbol' } } }
4.main 修改(
locale 可以更新语言
)
const i18n = new VueI18n({ locale: 'en-US', // 语言标识
numberFormats
});
5.main修改
new Vue({ router, store, i18n, render: h => h(App) }).$mount('#app')
6.然后在vue里面写
<i >{{ $t("currency.style") }}</i>
就能显示出来了
7.在js里面写
this.$t('currency.style')
就能在js里面输出这个变量值
可以重构
numberFormats
===========================================================================================================================
切换语言
http://kazupon.github.io/vue-i18n/zh/guide/sfc.html#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95
单文件组件里面
<i18n> { "en": { "hello": "hello world!" }, "ja": { "hello": "こんにちは、世界!" } } </i18n> <template> <div id="app"> <label for="locale">locale</label> <select v-model="locale"> <option>en</option> <option>ja</option> </select> <p>message: {{ $t('hello') }}</p> </div> </template> <script> export default { name: 'app', data () { return { locale: 'en' } }, watch: { locale (val) { this.$i18n.locale = val } } } </script>
http://kazupon.github.io/vue-i18n/zh/guide/locale.html
或者这样,都可以切换
<template> <div class="locale-changer"> <select v-model="$i18n.locale"> <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option> </select> </div> </template> <script> export default { name: 'locale-changer', data () { return { langs: ['ja', 'en'] } } } </script>
========================================================================================================================
延迟加载
一次加载所有翻译文件是过度和不必要的。
http://kazupon.github.io/vue-i18n/zh/guide/lazy-loading.html
在进入router之前先等待获取数据,然后next();
router.beforeEach((to, from, next) => { const lang = to.params.lang loadLanguageAsync(lang).then(() => next()) })
分类:
vue相关
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~