前端筆記(12)nuxt js 多語言方案

  1. 使用vue-i18n實現國際化,多語言數據保存在locales文件夾內;
  2. 通過URL的paramsvuex共同維護當前語言狀態;
  3. 路由改變時觸發middleware/i18n.js中間件,如果當前路由不包含多語言即params.lang爲空,重定向到當前語言。 最後調用commit('SET_LANG'),並修改i18n.locale

nuxt.config.js
前端路由國際化處理

router: {
    // 國際化中間件
    middleware: 'i18n',
    extendRoutes (routes) {
      // 路由國際化處理
      routes.forEach((r) => {
        if (r.path === '/') {
          r.path = `/:lang(${locales.join('|')})?`
        } else {
          r.path = `/:lang(${locales.join('|')})?${r.path}`
        }
      })
      ...
  },

./pugins/i18n.js
國際化插件初始化vue-i18n

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import zhCn from '@/locales/zh-cn'
import enUs from '@/locales/en-us'
import zhHk from '@/locales/zh-hk'
Vue.use(VueI18n)

export default ({ app, store }) => {
  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: 'en-us',
    messages: {
      'zh-cn': zhCn,
      'zh-hk': zhHk,
      'en-us': enUs
    }
  })
}

./locales
國際化文件目錄

locales
├─zh-hk
|   ├─index.js                 //導出語言模塊
|   ├─modules                  // 多語言模塊化 
|   |    ├─about.js
|   |    ├─business.js
|   |    └index.js             // 掃描modules目錄整合所有模塊
├─zh-cn
|   ├─index.js
|   ├─modules
|   |    ├─about.js
|   |    ├─business.js
|   |    └index.js
├─en-us
|   ├─index.js
|   ├─modules
|   |    ├─about.js
|   |    ├─business.js
|   |    └index.js

/locales/zh-hk/modules/index.js
整合模塊,項目中多處使用

// 掃描目錄,整合所有模塊
const files = require.context('.', false, /\.js$/)
const modules = {}

files.keys().forEach((key) => {
  if (key === './index.js') { return }
  modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

export default modules

./client/middleware
國際化中間件

export default function ({ isHMR, app, store, params, error, req, route, redirect }) {
  // 未匹配到任何路由
  if (!route.matched || route.matched.length <= 0) {
    return error({ message: 'This page could not be found.', statusCode: 404 })
  }
  // nodemon熱更新忽略
  if (isHMR) { return }
  // 確定當前語言
  const locale = params.lang || store.state.locale || app.i18n.fallbackLocale
  // 重定向到多語言
  if (!params.lang & route.fullPath === '/') {
    return redirect(`/${locale}`)
  } else if (!params.lang) {
    return redirect(`/${locale}${route.fullPath}`)
  }
  // 設置語言
  store.commit('SET_LANG', locale)
  app.i18n.locale = store.state.locale
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章