Nuxt.js配置国际化

介绍

使用vue-i18n插件对Nuxt.js 配置国际化,切换多种语言, 配合element-ui

以配置中英文两种语言为例

所有语言和选择的语言存储在vuex

安装

安装国际化插件vue-i18n

npm i vue-i18n --save

添加locales文件

  • 在根目录下新建目录locales/
  • locales/目录下新建en.json文件,对应英文
{ "links": { "home": "Home", "about": "About" }, "home": { "title": "Welcome", "introduction": "This is an introduction in English." }, "about": { "title": "About", "introduction": "This page is made to give you more informations." } }
  • locales/目录下新建zh.json文件,对应中文
{ "links": { "home": "首页", "about": "关于" }, "home": { "title": "欢迎", "introduction": "汉语中的介绍部分" }, "about": { "title": "关于", "introduction": "该页面用于提供更多的关于我们信息" } }

配置vuex

  • 修改store/index.js文件,添加localeslocale
// ... import Cookies from 'js-cookie' // ... export const state = () => ({ locales: ['en', 'zh'], locale: 'zh', // ... }) // ... export const mutations = { setLang(state, locale) { if (state.locales.includes(locale)) { state.locale = locale Cookies.set('lang', locale) } }, // ... } // ...

添加插件配置

这里是配合element-ui,可以将element-uivue-i18n配置写在同一个js文件中

这里分开写,假设已经配置好plugins/element-ui.js文件了

  • 修改plugins/element-ui.js,将里面配置语言相关代码注释掉
// import lang from 'element-ui/lib/locale/lang/en' // import locale from 'element-ui/lib/locale' // // 设置语言 // locale.use(lang)
  • plugins/目录下新建vue-i18n.js文件
import Vue from 'vue' import VueI18n from 'vue-i18n' import enLocale from 'element-ui/lib/locale/lang/en' import zhLocale from 'element-ui/lib/locale/lang/zh-CN' import ElementLocale from 'element-ui/lib/locale' Vue.use(VueI18n) export default ({ app, store }) => { // Set i18n instance on app // This way we can use it in middleware and pages asyncData/fetch app.i18n = new VueI18n({ locale: store.state.locale, fallbackLocale: 'en', messages: { 'en': { ...require('~/locales/en.json'), ...enLocale }, 'zh': { ...require('~/locales/zh.json'), ...zhLocale } } }) // app.i18n.path = (link) => { // if (app.i18n.locale === app.i18n.fallbackLocale) { // return `/${link}` // } // return `/${app.i18n.locale}/${link}` // } // 配置element-ui的组件国际化 ElementLocale.i18n((key, value) => app.i18n.t(key, value)) }
  • 修改nuxt.config.js文件,添加vue-i18n配置(vue-i18n配置要放在element-ui配置的后面)
// ... module.exports = { // ... plugins: [ // ... { src: '@/plugins/element-ui', ssr: true }, { src: '@/plugins/vue-i18n', ssr: true }, // ... ], // ... }

组件中使用

<h1 class="Content__Title"> {{ $t('about.title') }} </h1>

切换语言

// ... export default { // ... methods: { // ... changeLang(locale) { // const locale = this.$store.state.locale === 'en' ? 'zh' : 'en' if (this.$store.state.locales.indexOf(locale) !== -1) { this.$i18n.locale = locale this.$store.commit('setLang', locale) } }, // ... } // ... }

创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: