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())
})

 

posted on   chenyi4  阅读(739)  评论(0编辑  收藏  举报

编辑推荐:
· 从 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的设计差异
· 三行代码完成国际化适配,妙~啊~

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示