nuxt系列【三】nuxt + element-ui + nuxt-i18n国际化,实现多语言

这里以中英文切换为例:

1. 安装nuxt-i18n

npm install nuxt-i18n -S

2.新建lang 文件夹,放置语言包

zh.js 


const zh = {
  webTitle:'我的 nuxt.js 例子',
  index: '首页',
  list:'列表'
}
export default zh

en.js

const en = {
  webTitle:'my nuxt.js demo',
  index: 'Home',
  list:'list'
}
export default en

3.新建i18n.js 配置文件

import zh from './lang/zh'
import en from './lang/en'

// 加载element-ui语言包
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'

const mergeZH = Object.assign(zhLocale.default, zh);
const mergeEN = Object.assign(enLocale.default, en);

const I18N = {
  locales: [{
      code: 'en',
      iso: 'en-US',
      name: 'English'
    },
    {
      code: 'zh',
      iso: 'zh-ZH',
      name: '中文'
    }
  ],
  defaultLocale: 'zh',
  vueI18n: {
    fallbackLocale: 'zh',
    messages: {
      en: mergeEN,
      zh: mergeZH
    }
  }
}

export default I18N

4.添加中间件:lang.js,切换语言时,更改路由,同时更新store中语言类型

import getCookie from '@/config/get-cookie'

export default function ({store, route, redirect, req}) {
  const {lang} = getCookie(req)
  if (lang) {
    store.commit('setLang', lang)
  }
  const routePath = route.path
  if (store.state.lang === 'en' && routePath.indexOf(`/${store.state.lang}/`) === -1) {
    console.log('redirect')
    return redirect({path: `/${store.state.lang}${routePath}`, query: route.query})
  }
}

store中添加mutaion:

      setLang(state, lang) {
        state.lang = lang
      }

 

5.在nuxt.js中配置module

import I18N from './config/i18n'

module.exports = {

  modules: [
    ['nuxt-i18n', I18N],
  ]

}

6. plugins/element-ui.js

import Vue from 'vue'
import Element from 'element-ui/lib/element-ui.common'
export default ({
  app
}) => {
  Vue.use(Element, {
    i18n: (key, value) => app.i18n.t(key, value)
  })
}

6.切换语言组件




demo参考:https://github.com/liuzhumin/nuxt-demo.git

你可能感兴趣的:(Javascript,nuxt)