vue-i18n language prefix in url output
There is a fully working site where 2 languages all work fine. But the problem is that the url should display the language and remain on the same page when the language is changed, and the url has changed.
What I would like to achieve (site.com/ru/about) and (site.com/en/about)
i18n.js
import VueI18n from 'vue-i18n'
import Vue from 'vue'
import { DEFAULT_LANGUAGE, FALLBACK_LANGUAGE } from '../constants/trans'
import ru from '../locales/ru.json'
Vue.use(VueI18n)
export const i18n = new VueI18n({
locale: DEFAULT_LANGUAGE, // set locale
fallbackLocale: FALLBACK_LANGUAGE,
messages: { ru }// set locale messages
})
Translation.js
import axios from 'axios'
import { SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE } from '../constants/trans'
import { i18n } from '../plugins/i18n'
const Trans = {
get defaultLanguage () {
return DEFAULT_LANGUAGE
},
get supportedLanguages () {
return SUPPORTED_LANGUAGES
},
get currentLanguage () {
return i18n.locale
},
set currentLanguage (lang) {
i18n.locale = lang
},
/**
* Gets the first supported language that matches the user's
* @return {String}
*/
getUserSupportedLang () {
const userPreferredLang = Trans.getUserLang()
// Check if user preferred browser lang is supported
if (Trans.isLangSupported(userPreferredLang.lang)) {
return userPreferredLang.lang
}
// Check if user preferred lang without the ISO is supported
if (Trans.isLangSupported(userPreferredLang.langNoISO)) {
return userPreferredLang.langNoISO
}
return Trans.defaultLanguage
},
/**
* Returns the users preferred language
*/
getUserLang () {
const lang = window.navigator.language || window.navigator.userLanguage || Trans.defaultLanguage
return {
lang: lang,
langNoISO: lang.split('-')[0]
}
},
/**
* Sets the language to various services (axios, the html tag etc)
* @param {String} lang
* @return {String} lang
*/
setI18nLanguageInServices (lang) {
Trans.currentLanguage = lang
axios.defaults.headers.common['Accept-Language'] = lang
document.querySelector('html').setAttribute('lang', lang)
return lang
},
/**
* Loads new translation messages and changes the language when finished
* @param lang
* @return {Promise<any>}
*/
changeLanguage (lang) {
if (!Trans.isLangSupported(lang)) return Promise.reject(new Error('Language not supported'))
if (i18n.locale === lang) return Promise.resolve(lang) // has been loaded prior
return Trans.loadLanguageFile(lang).then(msgs => {
i18n.setLocaleMessage(lang, msgs.default || msgs)
return Trans.setI18nLanguageInServices(lang)
})
},
/**
* Async loads a translation file
* @param lang
* @return {Promise<*>|*}
*/
loadLanguageFile (lang) {
return import(/* webpackChunkName: "lang-[request]" */ `@/locales/${lang}.json`)
},
/**
* Checks if a lang is supported
* @param {String} lang
* @return {boolean}
*/
isLangSupported (lang) {
return Trans.supportedLanguages.includes(lang)
},
/**
* Checks if the route's param is supported, if not, redirects to the first supported one.
* @param {Route} to
* @param {Route} from
* @param {Function} next
* @return {*}
*/
routeMiddleware (to, from, next) {
// Load async message files here
const lang = to.params.lang
if (!Trans.isLangSupported(lang)) return next(Trans.getUserSupportedLang())
return Trans.changeLanguage(lang).then(() => next())
}
}
export { Trans }
index.js (router)
....
import {i18n} from '../plugins/i18n'
import {DEFAULT_LANGUAGE} from '../constants/trans.js'
Vue.use(Router);
Vue.use(Meta)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: '/calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: '/portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: '/contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
]
});
I tried to start like this .. and then I don’t know what to do.
export default new Router({
routes: [
{
path: '/',
redirect: `/${DEFAULT_LANGUAGE}`,
},
{
path: '/:locale',
component: {
template: '<router-view />',
},
children: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: 'calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: 'portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: 'contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
],
},
],
})
vue.js vuejs2 internationalization
add a comment |
There is a fully working site where 2 languages all work fine. But the problem is that the url should display the language and remain on the same page when the language is changed, and the url has changed.
What I would like to achieve (site.com/ru/about) and (site.com/en/about)
i18n.js
import VueI18n from 'vue-i18n'
import Vue from 'vue'
import { DEFAULT_LANGUAGE, FALLBACK_LANGUAGE } from '../constants/trans'
import ru from '../locales/ru.json'
Vue.use(VueI18n)
export const i18n = new VueI18n({
locale: DEFAULT_LANGUAGE, // set locale
fallbackLocale: FALLBACK_LANGUAGE,
messages: { ru }// set locale messages
})
Translation.js
import axios from 'axios'
import { SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE } from '../constants/trans'
import { i18n } from '../plugins/i18n'
const Trans = {
get defaultLanguage () {
return DEFAULT_LANGUAGE
},
get supportedLanguages () {
return SUPPORTED_LANGUAGES
},
get currentLanguage () {
return i18n.locale
},
set currentLanguage (lang) {
i18n.locale = lang
},
/**
* Gets the first supported language that matches the user's
* @return {String}
*/
getUserSupportedLang () {
const userPreferredLang = Trans.getUserLang()
// Check if user preferred browser lang is supported
if (Trans.isLangSupported(userPreferredLang.lang)) {
return userPreferredLang.lang
}
// Check if user preferred lang without the ISO is supported
if (Trans.isLangSupported(userPreferredLang.langNoISO)) {
return userPreferredLang.langNoISO
}
return Trans.defaultLanguage
},
/**
* Returns the users preferred language
*/
getUserLang () {
const lang = window.navigator.language || window.navigator.userLanguage || Trans.defaultLanguage
return {
lang: lang,
langNoISO: lang.split('-')[0]
}
},
/**
* Sets the language to various services (axios, the html tag etc)
* @param {String} lang
* @return {String} lang
*/
setI18nLanguageInServices (lang) {
Trans.currentLanguage = lang
axios.defaults.headers.common['Accept-Language'] = lang
document.querySelector('html').setAttribute('lang', lang)
return lang
},
/**
* Loads new translation messages and changes the language when finished
* @param lang
* @return {Promise<any>}
*/
changeLanguage (lang) {
if (!Trans.isLangSupported(lang)) return Promise.reject(new Error('Language not supported'))
if (i18n.locale === lang) return Promise.resolve(lang) // has been loaded prior
return Trans.loadLanguageFile(lang).then(msgs => {
i18n.setLocaleMessage(lang, msgs.default || msgs)
return Trans.setI18nLanguageInServices(lang)
})
},
/**
* Async loads a translation file
* @param lang
* @return {Promise<*>|*}
*/
loadLanguageFile (lang) {
return import(/* webpackChunkName: "lang-[request]" */ `@/locales/${lang}.json`)
},
/**
* Checks if a lang is supported
* @param {String} lang
* @return {boolean}
*/
isLangSupported (lang) {
return Trans.supportedLanguages.includes(lang)
},
/**
* Checks if the route's param is supported, if not, redirects to the first supported one.
* @param {Route} to
* @param {Route} from
* @param {Function} next
* @return {*}
*/
routeMiddleware (to, from, next) {
// Load async message files here
const lang = to.params.lang
if (!Trans.isLangSupported(lang)) return next(Trans.getUserSupportedLang())
return Trans.changeLanguage(lang).then(() => next())
}
}
export { Trans }
index.js (router)
....
import {i18n} from '../plugins/i18n'
import {DEFAULT_LANGUAGE} from '../constants/trans.js'
Vue.use(Router);
Vue.use(Meta)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: '/calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: '/portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: '/contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
]
});
I tried to start like this .. and then I don’t know what to do.
export default new Router({
routes: [
{
path: '/',
redirect: `/${DEFAULT_LANGUAGE}`,
},
{
path: '/:locale',
component: {
template: '<router-view />',
},
children: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: 'calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: 'portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: 'contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
],
},
],
})
vue.js vuejs2 internationalization
Look into using eitherbasePath
or parameters with your router.
– Simon Hyll
Dec 29 '18 at 9:36
add a comment |
There is a fully working site where 2 languages all work fine. But the problem is that the url should display the language and remain on the same page when the language is changed, and the url has changed.
What I would like to achieve (site.com/ru/about) and (site.com/en/about)
i18n.js
import VueI18n from 'vue-i18n'
import Vue from 'vue'
import { DEFAULT_LANGUAGE, FALLBACK_LANGUAGE } from '../constants/trans'
import ru from '../locales/ru.json'
Vue.use(VueI18n)
export const i18n = new VueI18n({
locale: DEFAULT_LANGUAGE, // set locale
fallbackLocale: FALLBACK_LANGUAGE,
messages: { ru }// set locale messages
})
Translation.js
import axios from 'axios'
import { SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE } from '../constants/trans'
import { i18n } from '../plugins/i18n'
const Trans = {
get defaultLanguage () {
return DEFAULT_LANGUAGE
},
get supportedLanguages () {
return SUPPORTED_LANGUAGES
},
get currentLanguage () {
return i18n.locale
},
set currentLanguage (lang) {
i18n.locale = lang
},
/**
* Gets the first supported language that matches the user's
* @return {String}
*/
getUserSupportedLang () {
const userPreferredLang = Trans.getUserLang()
// Check if user preferred browser lang is supported
if (Trans.isLangSupported(userPreferredLang.lang)) {
return userPreferredLang.lang
}
// Check if user preferred lang without the ISO is supported
if (Trans.isLangSupported(userPreferredLang.langNoISO)) {
return userPreferredLang.langNoISO
}
return Trans.defaultLanguage
},
/**
* Returns the users preferred language
*/
getUserLang () {
const lang = window.navigator.language || window.navigator.userLanguage || Trans.defaultLanguage
return {
lang: lang,
langNoISO: lang.split('-')[0]
}
},
/**
* Sets the language to various services (axios, the html tag etc)
* @param {String} lang
* @return {String} lang
*/
setI18nLanguageInServices (lang) {
Trans.currentLanguage = lang
axios.defaults.headers.common['Accept-Language'] = lang
document.querySelector('html').setAttribute('lang', lang)
return lang
},
/**
* Loads new translation messages and changes the language when finished
* @param lang
* @return {Promise<any>}
*/
changeLanguage (lang) {
if (!Trans.isLangSupported(lang)) return Promise.reject(new Error('Language not supported'))
if (i18n.locale === lang) return Promise.resolve(lang) // has been loaded prior
return Trans.loadLanguageFile(lang).then(msgs => {
i18n.setLocaleMessage(lang, msgs.default || msgs)
return Trans.setI18nLanguageInServices(lang)
})
},
/**
* Async loads a translation file
* @param lang
* @return {Promise<*>|*}
*/
loadLanguageFile (lang) {
return import(/* webpackChunkName: "lang-[request]" */ `@/locales/${lang}.json`)
},
/**
* Checks if a lang is supported
* @param {String} lang
* @return {boolean}
*/
isLangSupported (lang) {
return Trans.supportedLanguages.includes(lang)
},
/**
* Checks if the route's param is supported, if not, redirects to the first supported one.
* @param {Route} to
* @param {Route} from
* @param {Function} next
* @return {*}
*/
routeMiddleware (to, from, next) {
// Load async message files here
const lang = to.params.lang
if (!Trans.isLangSupported(lang)) return next(Trans.getUserSupportedLang())
return Trans.changeLanguage(lang).then(() => next())
}
}
export { Trans }
index.js (router)
....
import {i18n} from '../plugins/i18n'
import {DEFAULT_LANGUAGE} from '../constants/trans.js'
Vue.use(Router);
Vue.use(Meta)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: '/calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: '/portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: '/contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
]
});
I tried to start like this .. and then I don’t know what to do.
export default new Router({
routes: [
{
path: '/',
redirect: `/${DEFAULT_LANGUAGE}`,
},
{
path: '/:locale',
component: {
template: '<router-view />',
},
children: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: 'calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: 'portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: 'contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
],
},
],
})
vue.js vuejs2 internationalization
There is a fully working site where 2 languages all work fine. But the problem is that the url should display the language and remain on the same page when the language is changed, and the url has changed.
What I would like to achieve (site.com/ru/about) and (site.com/en/about)
i18n.js
import VueI18n from 'vue-i18n'
import Vue from 'vue'
import { DEFAULT_LANGUAGE, FALLBACK_LANGUAGE } from '../constants/trans'
import ru from '../locales/ru.json'
Vue.use(VueI18n)
export const i18n = new VueI18n({
locale: DEFAULT_LANGUAGE, // set locale
fallbackLocale: FALLBACK_LANGUAGE,
messages: { ru }// set locale messages
})
Translation.js
import axios from 'axios'
import { SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE } from '../constants/trans'
import { i18n } from '../plugins/i18n'
const Trans = {
get defaultLanguage () {
return DEFAULT_LANGUAGE
},
get supportedLanguages () {
return SUPPORTED_LANGUAGES
},
get currentLanguage () {
return i18n.locale
},
set currentLanguage (lang) {
i18n.locale = lang
},
/**
* Gets the first supported language that matches the user's
* @return {String}
*/
getUserSupportedLang () {
const userPreferredLang = Trans.getUserLang()
// Check if user preferred browser lang is supported
if (Trans.isLangSupported(userPreferredLang.lang)) {
return userPreferredLang.lang
}
// Check if user preferred lang without the ISO is supported
if (Trans.isLangSupported(userPreferredLang.langNoISO)) {
return userPreferredLang.langNoISO
}
return Trans.defaultLanguage
},
/**
* Returns the users preferred language
*/
getUserLang () {
const lang = window.navigator.language || window.navigator.userLanguage || Trans.defaultLanguage
return {
lang: lang,
langNoISO: lang.split('-')[0]
}
},
/**
* Sets the language to various services (axios, the html tag etc)
* @param {String} lang
* @return {String} lang
*/
setI18nLanguageInServices (lang) {
Trans.currentLanguage = lang
axios.defaults.headers.common['Accept-Language'] = lang
document.querySelector('html').setAttribute('lang', lang)
return lang
},
/**
* Loads new translation messages and changes the language when finished
* @param lang
* @return {Promise<any>}
*/
changeLanguage (lang) {
if (!Trans.isLangSupported(lang)) return Promise.reject(new Error('Language not supported'))
if (i18n.locale === lang) return Promise.resolve(lang) // has been loaded prior
return Trans.loadLanguageFile(lang).then(msgs => {
i18n.setLocaleMessage(lang, msgs.default || msgs)
return Trans.setI18nLanguageInServices(lang)
})
},
/**
* Async loads a translation file
* @param lang
* @return {Promise<*>|*}
*/
loadLanguageFile (lang) {
return import(/* webpackChunkName: "lang-[request]" */ `@/locales/${lang}.json`)
},
/**
* Checks if a lang is supported
* @param {String} lang
* @return {boolean}
*/
isLangSupported (lang) {
return Trans.supportedLanguages.includes(lang)
},
/**
* Checks if the route's param is supported, if not, redirects to the first supported one.
* @param {Route} to
* @param {Route} from
* @param {Function} next
* @return {*}
*/
routeMiddleware (to, from, next) {
// Load async message files here
const lang = to.params.lang
if (!Trans.isLangSupported(lang)) return next(Trans.getUserSupportedLang())
return Trans.changeLanguage(lang).then(() => next())
}
}
export { Trans }
index.js (router)
....
import {i18n} from '../plugins/i18n'
import {DEFAULT_LANGUAGE} from '../constants/trans.js'
Vue.use(Router);
Vue.use(Meta)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: '/calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: '/portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: '/contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
]
});
I tried to start like this .. and then I don’t know what to do.
export default new Router({
routes: [
{
path: '/',
redirect: `/${DEFAULT_LANGUAGE}`,
},
{
path: '/:locale',
component: {
template: '<router-view />',
},
children: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: 'calculator',
name: 'Calculator',
component: PageCalculator
},
{
path: 'portfolio',
name: 'Portfolio',
component: PageProject
},
{
path: 'contact',
name: 'Contact',
component: PageContact
},
{
path: '*',
redirect: '/'
}
],
},
],
})
vue.js vuejs2 internationalization
vue.js vuejs2 internationalization
edited Jan 2 at 7:34
Pavel8289
asked Dec 29 '18 at 6:09
Pavel8289Pavel8289
167
167
Look into using eitherbasePath
or parameters with your router.
– Simon Hyll
Dec 29 '18 at 9:36
add a comment |
Look into using eitherbasePath
or parameters with your router.
– Simon Hyll
Dec 29 '18 at 9:36
Look into using either
basePath
or parameters with your router.– Simon Hyll
Dec 29 '18 at 9:36
Look into using either
basePath
or parameters with your router.– Simon Hyll
Dec 29 '18 at 9:36
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53967160%2fvue-i18n-language-prefix-in-url-output%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53967160%2fvue-i18n-language-prefix-in-url-output%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Look into using either
basePath
or parameters with your router.– Simon Hyll
Dec 29 '18 at 9:36