Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation with vue-router #50

Open
kskrlin opened this issue Nov 30, 2017 · 32 comments
Open

Implementation with vue-router #50

kskrlin opened this issue Nov 30, 2017 · 32 comments

Comments

@kskrlin
Copy link

kskrlin commented Nov 30, 2017

Is there a documentation or an example how to use this plugin with vue-router to add language prefixes to routes and to translate route names?

@tikiatua
Copy link
Member

tikiatua commented Nov 30, 2017

Hi @kikky7,

There is currently no example for this. But I would recommend to pass the language key via a property i.e. /:locale/somepath and then set the locale using a router.beforeEach navigation guard https://router.vuejs.org/en/advanced/navigation-guards.html.

To do this, you need to initialize the routes while passing the respective vue instance to the init function (see #19 for an example of an init function).

Please let me know, if you need any further assistance or a more complete example.

@ghost
Copy link

ghost commented Dec 12, 2017

Hello @tikiatua I just came across this and would love to have an example of how this can be done.

@tikiatua
Copy link
Member

Hi @andrade1379,

I will add an example tomorrow.

@tikiatua
Copy link
Member

Hi there,

I added an example with vue-router in the test directory. Basically you need to call the function Vue.i18n.set(locale) from the route guard.

// initialize a new vuex store including our i18nVuexModule
const store = new Vuex.Store();

// initialize the vuexi18nPlugin
Vue.use(vuexI18n.plugin, store, {
  onTranslationNotFound: function(locale, key) {
    console.warn(`vuex-i18n :: Key '${key}' not found for locale '${locale}'`);
  }
});

// use vue router to illustrate how to use route matching to set the locale
Vue.use(VueRouter);

// define an init function for the router
let router = new VueRouter({
  routes: [{
    path: '/:lang'
  }]
});

// use beforeEach route guard to set the language
router.beforeEach((to, from, next) => {

  // use the language from the routing param or default language
  let language = to.params.lang;
  if (!language) {
    language = 'en';
  }

  // set the current language for vuex-i18n. note that translation data
  // for the language might need to be loaded first
  Vue.i18n.set(language);
  next();
  
});

@madebysoren
Copy link

This seems really promising. However I will still end up in a range of paths that looks like this:

domain.com/en/home
domain.com/fr/home
domain.com/dk/home

That doesn't really fit into my needs, which is more like this:

domain.com/en/home
domain.com/fr/accueil
domain.com/dk/hjem

Is there anyway we can support dynamic language-dependent paths without having to write this:

routes: [{
    path: '/:lang',
    children: [
      {
        path: 'home', // en
        component: home
      },
      {
        path: 'accueil', // fr
        component: home
      },
      {
        path: 'hjem', // dk
        component: home
      }
    ]
  }]

... but instead this, which I would much rather use:

routes: [{
    path: '/:lang',
    children: [
      {
        path: $t('path_home'), // en, fra, dk
        component: home
      }
    ]
  }]

@tikiatua tikiatua reopened this Feb 21, 2018
@madebysoren
Copy link

If you have any ideas on how to approach this, I have some time to work a bit with this. Please let me know.

@kskrlin
Copy link
Author

kskrlin commented Mar 1, 2018

I developed few projects with similar/same requirements so when I have time I will post an examples, but give me a timeframe of a week or so.

@madebysoren
Copy link

@kikky7 Cool. I just got an idea of using wildcard and then redirect based on the specific language-dependent route names. Something like this:

routes: [{
    path: '/:lang',
    children: [
      {
        path: '*'
        redirect: to => {
          // do something brilliant here
        }
      }
    ]
  }]

Is your approach something similar?

@ghost
Copy link

ghost commented Apr 25, 2018

@kikky7 Can you share?

@kskrlin
Copy link
Author

kskrlin commented Apr 25, 2018

@atilkan Yes, I will try in next 2 days, I am very busy these last weeks.

@BruDroid
Copy link

@kikky7 I'm also looking into this. An example would be very awesome.

+1

@dkfbasel dkfbasel deleted a comment from grzegorztomasiak Jun 19, 2018
@ghost
Copy link

ghost commented Jun 19, 2018

@tikiatua What was that comment? It is already in my mailbox though.

@tikiatua
Copy link
Member

Hi everyone,

I deleted the comment as it was not helpful and insulting towards a commenter.

@kskrlin
Copy link
Author

kskrlin commented Jun 30, 2018

I am sorry for delay, but I didn't find any simple solution as in some examples here, also my every project wasn't implemented with full routes translations in the end (only with language change in url), but here is some sample code how you can achieve such solution. It's a little bit of a hack, but as tested, it makes the work done.

https://github.com/kikky7/vue-localized-routes-example

@stalniy
Copy link

stalniy commented Aug 23, 2018

The easy way to do it is to use translations as proposed by @madebysoren + full page reload

@akuma06
Copy link

akuma06 commented Aug 25, 2018

Hi! I think I would do something like this:

  • First, you need to have preloaded i18n with the languages
  • Second you do the default routes:
const defaultRoutes = [{
      path: 'home',
      component: Home
   },
   {
      path: 'contact',
      component: Contact
  },
  {
      path: 'about', 
      component: About
}]
const languages = i18n.locales() // get the available languages
const routes = [] // Should contain all the routes
languages.forEach(lang => {
  defaultRoutes.forEach(route => {
    routes.push({
      path: '/'+lang+'/'+i18n.t(route.path),
      component: route.component
    })
  })
})

@stalniy
Copy link

stalniy commented Aug 26, 2018

It’s good solution but probably will require all languages to be loaded otherwise there will be a bunch of warnings and eventually route path won’t be translated.

However, if we extract all route translations into one file and load it as part of the app bundle, all should be good :)

@gomezmark
Copy link

gomezmark commented Oct 5, 2018

Hi guys,

How about this one?

methods: {
    changeLocale () {
      let lang = this.$store.state.locale === 'en' ? 'ar' : 'en'

      this.$store.dispatch('setLang', lang)
      this.$router.push({
        name: this.$route.name === 'index' ? 'lang' : this.$route.name,
        params: {
          lang: lang
        }
      })
    }

@brickgale
Copy link

Hi guys,

right now i'm using this weird solution

let routes = [
	{
		path: '',
		name: 'home',
		component: Home,
	},
	{
		path: Vue.i18n.translate('/login'),
		name: 'login',
		component: Login,
	},
        ...
]

it's kinda hassle adding Vue.i18n.translate() function on every path on route. is there any cleaner solution for this? note: prefixing isn't really in my use case

@tikiatua
Copy link
Member

Hi everyone,

I will be presenting vuex-i18n at a Vue meet up in Switzerland and plan to make an additional module to somehow patch vue-router to easily make localized routes available.

@ghost
Copy link

ghost commented Oct 17, 2018

Hi everyone,

I will be presenting vuex-i18n at a Vue meet up in Switzerland and plan to make an additional module to somehow patch vue-router to easily make localized routes available.

Will you supply a link to your talk or slides?

@tikiatua
Copy link
Member

Sure. The meetup is on November 15th. I will supply the link to the presentation just afterwards.

@CelticParser
Copy link

@tikiatua
Are you still working on that patch? Plz say yes - LOL

@guins
Copy link

guins commented Jan 10, 2019

This is how I solved this issue. Knowing that I needed my different paths to work in all languages (for lang switching directly in the app without reloading):

// Current locale (your preferred way to get it)
const currentLocale = 'en';

// Object of all localized paths (with the key mapping the route `name`)
const localizedRoutesPaths = {
  en: {
    movies: 'movies'
  },
  fr: {
    movies: 'film'
  }
};

// Simple routes list (with only the `name` attribute for localized routes)
const routes = [
  {
    path: '/:locale',
    component: MainViewContainer,
    children: [
      {
        name: 'movies',
        component: MoviesView
      }
    ]
  }
],

// Recursive for loop adding the `path` and `alias` attributes to each localized route
function routeForEachHandler(route, index) {
  if( route.name && localizedRoutesPaths[currentLocale].hasOwnProperty(route.name) )
  {
    // Get route path in current language
    route.path = localizedRoutesPaths[currentLocale][route.name]

    // ONLY IF YOU NEED PATH NAMES TO WORK FOR ALL LANGUAGES
    // Get array of route paths of other languages for aliases
    route.alias = Object.keys(localizedRoutesPaths).reduce((accumulator, key) => {
      const localizedPath = localizedRoutesPaths[key][route.name]
      // Check if all true :
      // it's not the current language
      // it's not the same path name in this other language (otherwise it will create a infinite loop)
      // it's not already in the aliases list (otherwise it will also create a infinite loop)
      if( key !== currentLocale
        && localizedPath !== route.path
        && accumulator.indexOf(localizedPath) < 0
      ){
        accumulator.push(localizedRoutesPaths[key][route.name]);
      }
      return accumulator;
    }, []);
  }

  if( route.children ){
    route.children.forEach(routeForEachHandler)
  }
}

routes.forEach(routeForEachHandler);

const router = new VueRouter ({
  routes
});

@narender2031
Copy link

narender2031 commented May 10, 2019

I required my routes like this :-

domain.com/en/home
domain.com/fr/accueil
domain.com/dk/hjem

@tikiatua any solution for this.

@tikiatua
Copy link
Member

Hi @narender2031

You should be able to implement this with the solution of @guins listed above. This will register the respective routes with vue router using the vue-router alias feature.

What you need to do additionally is create a beforeRoute hook, that sets the locale to the :locale param of the route, when a user visits a specific route.

I still plan to make the whole setup simpler by providing a vue-router plugin that should help with this, but will likely not be able to work on this before later in summer.

@adi3230
Copy link

adi3230 commented May 27, 2019

Currently trying out as mentioned above

const routes = [
    {
        path: '/abc/',
        name: 'ParentComponent',
        component: ParentComponent,
        children: [
            // Add routes here
            {
                name: 'stepone',
                component: StepOne,
            },
            {
                name: 'steptwo',
                component: StepTwo,
            },
            {
                path: '*',
                redirect: '/abc/xyz',
            },
        ],
    },
];
routes.forEach((route) => {
    if (route.children) {
        route.children.forEach((childRoute) => {
            if (childRoute.name === translations[currentLocale][childRoute.name]) {
                childRoute.path = translations[currentLocale][childRoute.name];
            }
        });
    }
});

const router = new Router({
    mode: 'history',
    base: `${getLocale}`,
    routes,
});

Currently I am not able to set the route path at runtime and obvious vue-router complains that it doesn't find path. I want to localize the urls for the child route paths.
Currently I have no idea how to proceed further
@tikiatua @guins Can you please point out what I am doing here wrong

@narender2031
Copy link

narender2031 commented May 27, 2019

In your locale helper.js, there is a method

export const defaultI18n = () => {
  return new VueI18n({
    locale: getLocale(),
    fallbackLocale: 'de',
    messages
  });
};

you need to import this method in your routes.js file
import { defaultI18n } from '../locales/helper'

then

export default [
  { path: '/:locale*/' + i18n.t('routes.city_name'), component: city },
];

@adi3230 try this if you are using I18n for locale

@adi3230
Copy link

adi3230 commented May 27, 2019

@narender2031 It worked thanks

@tikiatua tikiatua added this to To do in Version 2.0.0 Aug 21, 2019
@michaelKaefer
Copy link

michaelKaefer commented Dec 31, 2019

Is there any kind of official solution yet? I think a lot of people will need:

domain.com/en/home
domain.com/fr/accueil
domain.com/dk/hjem

@stalniy
Copy link

stalniy commented Dec 31, 2019

I have a pretty good solution without boilerplate. I plan to write an article about it during the next 2 weeks

You can take a look here - https://www.minucreditinfo.ee/et/

Maybe later if everybody is ok with the implementation it can be back ported into Vue-i18n

@radek-altof
Copy link

Hey guys, I created Vue plugin exactly for this purpose. It leverages router alias and beforeEach hook, but that's all under the hood. If anybody's interested, check it out here:
https://www.npmjs.com/package/vue-lang-router

I also supplied it with a Vue CLI plugin for an easy installation, so it's as simple to add as
vue add lang-router

Feedback is welcome :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Version 2.0.0
  
To do
Development

No branches or pull requests