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

完成!

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

猜你喜欢

转载自www.cnblogs.com/lwl0812/p/10170480.html