Skip to content

Commit

Permalink
Merge pull request #129 from Yama-Tomo/master
Browse files Browse the repository at this point in the history
feat: i18n.locale property changes when route changed
  • Loading branch information
paulgv authored Oct 6, 2018
2 parents 2bc0f7d + 2f2f284 commit 66ba9f7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
6 changes: 6 additions & 0 deletions src/plugins/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export default async ({ app, route, store, req }) => {
app.i18n.routesNameSeparator = '<%= options.routesNameSeparator %>'
app.i18n.beforeLanguageSwitch = <%= options.beforeLanguageSwitch %>
app.i18n.onLanguageSwitched = <%= options.onLanguageSwitched %>
app.i18n.onRouteChanged = (to, from) => {}

if (store && store.state.localeDomains) {
app.i18n.locales.forEach(locale => {
Expand All @@ -74,6 +75,7 @@ export default async ({ app, route, store, req }) => {
}

app.i18n.locale = locale
app.i18n.nextLocale = locale

// Lazy-load translations
if (lazy) {
Expand All @@ -85,4 +87,8 @@ export default async ({ app, route, store, req }) => {
// Sync Vuex
syncVuex(locale, app.i18n.getLocaleMessage(locale))
}

if (!req) {
app.router.afterEach((to, from) => app.i18n.onRouteChanged(to, from))
}
}
18 changes: 13 additions & 5 deletions src/templates/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,17 +107,25 @@ middleware['i18n'] = async ({ app, req, res, route, store, redirect, isHMR }) =>

const oldLocale = app.i18n.locale
app.i18n.beforeLanguageSwitch(oldLocale, locale)

let messages = ''
// Lazy-loading enabled
if (lazy) {
const { loadLanguageAsync } = require('./utils')
const messages = await loadLanguageAsync(app.i18n, locale)
app.i18n.locale = locale
app.i18n.onLanguageSwitched(oldLocale, locale)
syncVuex(locale, messages)
messages = await loadLanguageAsync(app.i18n, locale)
} else {
// Lazy-loading disabled
messages = app.i18n.getLocaleMessage(locale)
}

// NOTE: `app.i18n.locale` property changes when route changed.
// but, `fetch` and `asyncData` methods is called before it is changed.
// if you using this property use `app.i18n.nextLocale` instead.
app.i18n.nextLocale = locale

app.i18n.onRouteChanged = (to, from) => {
app.i18n.locale = locale
app.i18n.onLanguageSwitched(oldLocale, locale)
syncVuex(locale, app.i18n.getLocaleMessage(locale))
syncVuex(locale, messages)
}
}

0 comments on commit 66ba9f7

Please sign in to comment.