最近在用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
若是有其餘方法,歡迎交流~~