diff --git a/src/plugins/main.js b/src/plugins/main.js index da785a8be..00f9aff25 100644 --- a/src/plugins/main.js +++ b/src/plugins/main.js @@ -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 => { @@ -74,6 +75,7 @@ export default async ({ app, route, store, req }) => { } app.i18n.locale = locale + app.i18n.nextLocale = locale // Lazy-load translations if (lazy) { @@ -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)) + } } diff --git a/src/templates/middleware.js b/src/templates/middleware.js index a84f6efa1..6d5ca8e5f 100644 --- a/src/templates/middleware.js +++ b/src/templates/middleware.js @@ -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) } }