Monday 31 December 2018

Translate vuejs route paths

I got this fine idea about translating routes paths, which doesn't sound so clever any more :), once I have encountered a problem. I hope you guys will see/find a solution.

This is my routes.js file, where routes are defined

export default [
    {
        path: '/:lang',
        component: {
            template: '<router-view></router-view>'
        },
        children: [
            {
                path: '',
                name: 'Home',
                component: load('Home')
            },
            {
                path: translatePath('contact'),
                name: 'Contact',
                component: load('Contact')
            },
            {
                path: translatePath('cookiePolicy'),
                name: 'CookiePolicy',
                component: load('CookiePolicy')
            },
        ]
    },
]

// and my simple function for translating paths
function translatePath(path) {
    let lang = Cookie.get('locale');

    let pathTranslations = {
        en: {
            contact: 'contact',
            cookiePolicy: 'cookie-policy',
        },
        sl: {
            contact: 'kontakt',
            cookiePolicy: 'piskotki',
        }
    };

    return pathTranslations[lang][path];
}

And this is my change language functionality in my component

setLocale(locale) {
    let selectedLanguage = locale.toLowerCase();
    this.$my.locale.setLocale(selectedLanguage); // update cookie locale
    console.log(this.$route.name);
    this.$router.replace({ name: this.$route.name, params: { lang: selectedLanguage } });
    location.reload();
},

The problem is following. When user executes the change language functionality I successfully change lang param, but the this.$route.name keeps the same in old language. Is there a way to "reload" routes, so there will be new routes paths, which will include proper language?

If you need any additional informations, please let me know and I will provide. Thank you!



from Translate vuejs route paths

No comments:

Post a Comment