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

5次阅读

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

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

  • nuxt.config.js
  • locales/index.js
  • locales/zh_CN.json
  • utils/config.js

# nuxt.config.js

module.exports = {
  // other code ...

  plugins: [{ src: '~/locales/index.js'} // locales 目录没有放置在 plugins 目录下主要是为了引用 json 文件方便
  ],

  // other code ...
}

# locales/index.js

从 Nuxt.js 应用国际化(i18n)的示例 变化而来 :

import Cookies from 'js-cookie'
import VueI18n from 'vue-i18n'
import Vue from 'vue'
Vue.use(VueI18n)

export default ({app, store}) => {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]] = Object.assign({}, require(`./${readDir[i]}.json`))
  }

  // Set i18n instance on app
  // This way we can use it in middleware and pages asyncData/fetch
  app.i18n = new VueI18n({
    locale,
    fallbackLocale: locale, // 语言环境中不存在相应 massage 键时回退到指定语言
    messages: data
  })
}

# locales/zh_CN.json

{
  "solutions":"解决方案",
  "global":{
    "login":"登录",
    "register":"注册",
    "logout":"注销",
    "join":"加入",
    "confirm":"确认",
    "submit":"提交",
    "reset":"重置",
    "all":"全部",
    "open":"打开",
    "close":"关闭",
    "userList": "用户列表"
  },
  "headerNav": {
    "home": "首页",
    "users":"用户"
  },
  "login": {
    "username": "用户名",
    "password": "密码"
  },
  "footer": {
    "TermsOfUse": "使用条款",
    "PrivacyPolicy": "隐私保护"
  }
}

调用方法 :
<h1 class="solutions">{{$t('solutions') }}</h1>

# utils/config.js

import Cookies from 'js-cookie'

const LangKey = 'hb_lang' // 语言

export function getLanguage() {return Cookies.get(LangKey)
}

export function setLanguage(data) {return Cookies.set(LangKey, data)
}

export function removeLanguage() {return Cookies.remove(LangKey)
}

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

import {setLanguage} from '~/utils/config.js'  
setLanguage('en_US')  

# 注意事项

以上配置须臾结合 Vue{{}} 进行编辑, 例如上文所提到的 :
<h1 class="solutions">{{$t('solutions') }}</h1>

倘若像下面这样则会导致切换语言时, 无法动态即时更新文案 :

// 不要这样写, 解决方法在下面
<template>
  <div>
    <div class="solutions">{{solutions}}</div>
  </div>
</template>

<script>
export default {data() {
    return {solutions : this.$t('solutions')
    }
  }
}
</script>

解决方法 :

<template>
  <div>
    <div class="solutions">{{solutions}}</div>
  </div>
</template>

<script>
export default {
  watch: {'$store.state.lang'(language) {this.init()
    }
  },
  data() {
    return {solutions : this.$t('solutions')
    }
  },
  created() {this.init()
  },
  methods: {init(){this.solutions = this.$t('solutions')
    }
  },
}
</script>

# 同系列的其他文章

  • Vue 项目中使用国际化,并配置动态切换语言的方法
正文完
 0