nuxt + vue-i18n 踩坑記錄


最近在用nuxt開發官網,同時支持多語言切換,所以又用到了 vue-i18n。

根據 nuxt 官網的demo,配置了 middleware 和 plugins

 

代碼如下:

// plugins/i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'

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: store.state.locale || 'cn',
    messages: {
      'cn': require('~/locales/cn.json'),
      'en': require('~/locales/en.json')
    }
  })

  app.i18n.path = (link) => {
    if (app.i18n.locale === app.i18n.fallbackLocale) {
      return `/${link}`
    }

    return `/${app.i18n.locale}/${link}`
  }
}
// middleware/i18n.js

export default function ({ isHMR, app, store, route, params, error, redirect }) {
  const defaultLocale = app.i18n.fallbackLocale
  // If middleware is called from hot module replacement, ignore it
  if (isHMR) return
  // Get locale from params
  const locale = params.lang || defaultLocale
  if (store.state.locales.indexOf(locale) === -1) {
    return error({ message: 'This page could not be found.', statusCode: 404 })
  }
  // Set locale
  store.commit('SET_LANG', locale)
  app.i18n.locale = store.state.locale
  // If route is /<defaultLocale>/... -> redirect to /...
  if (locale === defaultLocale && route.fullPath.indexOf('/' + defaultLocale) === 0) {
    const toReplace = '^/' + defaultLocale
    const re = new RegExp(toReplace)
    return redirect(
      route.fullPath.replace(re, '/')
    )
  }
}

 

emmmm,然后再加上一個語言切換的按鈕,一切都那么地完美!

export default {
    methods: {
      changeLanguage (language) {
        this.$i18n.locale = language
      }
    }
}

 

然鵝!試試看刷新,顯示的語言是用戶切換后的語言,該怎么做呢?

你可能第一時間想到的是保存在 localStorage 或 sessionStorage 中,因為我一開始就是這樣想的 T T

當然這是不行的,因為 nuxt 是服務端渲染,無法獲取到客戶端的window對象。

所以,最后決定,通過 cookie 來實現客戶端和服務端的通信。

廢話不多說了,直接上代碼:

export default {
    methods: {
      changeLanguage (language) {
        this.$i18n.locale = language
        document.cookie = "locale=" + language // 將當前語言保存到cookie 中,代碼僅作為演示,自己完善下哈
      }
    }
}
// middleware/i18n.js

import Cookie from 'cookie' // 新增

export default function ({ isHMR, app, store, route, params, error, redirect, req }) {
  const cookies = Cookie.parse(req.headers.cookie || '') // 新增
  const cookiesLocale = cookies['locale'] || ''  // 新增
  const defaultLocale = cookiesLocale || app.i18n.fallbackLocale  // 修改
  // 省略其他
}

 

完成!

 

如果有其他方法,歡迎交流~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM