nuxt + vue-i18n 踩坑记录

最近在用nuxt开发官网,同时支持多语言切换,因此又用到了 vue-i18n。vue

根据 nuxt 官网的demo,配置了 middleware 和 pluginsjson

 

代码以下:cookie

// 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,而后再加上一个语言切换的按钮,一切都那么地完美!session

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

 

然鹅!试试看刷新,显示的语言是用户切换后的语言,该怎么作呢?app

你可能第一时间想到的是保存在 localStorage 或 sessionStorage 中,由于我一开始就是这样想的 T Tasync

固然这是不行的,由于 nuxt 是服务端渲染,没法获取到客户端的window对象。fetch

因此,最后决定,经过 cookie 来实现客户端和服务端的通讯。ui

废话很少说了,直接上代码:this

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  // 修改
  // 省略其余
}

 

完成!spa

 

若是有其余方法,欢迎交流~~

相关文章
相关标签/搜索