Vue项目中使用国际化-并配置动态切换语言的方法

4次阅读

共计 1069 个字符,预计需要花费 3 分钟才能阅读完成。

主要由以下几个模块组成由:

  • src\main.js
  • src\locales\index.js
  • src\locales\zh_CN.json
  • src\utils\config.js

# src\main.js

import i18n from '@/locales/index.js'

new Vue({
  el: '#app',
  i18n,
  router,
  store,
  render: h => h(App)
})

# src\locales\index.js

import Cookies from 'js-cookie'
import VueI18n from 'vue-i18n'
import Vue from 'vue'

const data = {}
const locale = Cookies.get('hb_lang') || 'en_US'
const readDir = ['en_US', 'zh_CN', 'th_TH']
for (let i = 0; i < readDir.length; i++) {data[readDir[i]] = require(`./${readDir[i]}.json`)
}

Vue.use(VueI18n)
const i18n = new VueI18n({
  locale,
  fallbackLocale: locale, // 语言环境中不存在相应 massage 键时回退到指定语言
  messages: data
})

export default i18n

# src\locales\zh_CN.json

示例项目包涵中英泰三国语言, 这里仅抽出中文作为示例 :

{
  "欢迎登录": "欢迎登录",
  "参数配置":"参数配置",
  "折价币种":"折价币种"
}

调用方法 :
<h1 class="slogan">{{$t('欢迎登录') }}</h1>

# src\utils\config.js

import Cookies from 'js-cookie'
import i18n from '@/locales/index.js'
const Key = 'hb_lang'

export function get() {return Cookies.get(Key)
}

export function set(data) {
  i18n.locale = data
  return Cookies.set(Key, data)
}

export function remove() {return Cookies.remove(Key)
}

其中 , 当需要动态切换语言时,调用 set 方法即可,例如:

import {set as setLanguage} from '@/utils/config.js'

setLanguage('en_US')
正文完
 0