Automatically loading the user locale

Next, we can use navigator.language (or userLanguage for Internet Explorer compatibility) to retrieve the locale code. Then, we will check whether it is available in the langs list or if we have to use the default en locale.

  1. The getAutoLang function should look like this:
      export function getAutoLang () {
let result = window.navigator.userLanguage ||
window.navigator.language
if (result) {
result = result.substr(0, 2)
}
if (langs.indexOf(result) === -1) {
return 'en'
} else {
return result
}
}
Some browsers may return the code in the en-US format, but we only need the first two characters.
  1. In the src/main.js file, import the two new utility functions:
      import { createI18n, getAutoLang } from './utils/i18n'
  1. Then, modify the main function:
    1. Retrieve the preferred locale using getAutoLang.
    2. Create and wait for the i18n object with the createI18n function.
    3. Inject the i18n object into the root Vue instance.

It should now look like this:

async function main () {
const locale = getAutoLang()
const i18n = await createI18n(locale)
await store.dispatch('init')

// eslint-disable-next-line no-new
new Vue({
el: '#app',
router,
store,
i18n, // Inject i18n into the app
...App,
})
}
Don't forget the await keyword in front of createI18n, or else you will get the Promise instead.

You can now open the network pane in the browser devtools and refresh the page. The translations module corresponding to the selected locale will be loaded by webpack in a separate request. In this example screenshot, this is the 2.build.js file that is asynchronously loaded:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.9.115