Code Monkey home page Code Monkey logo

Comments (32)

madebysoren avatar madebysoren commented on May 25, 2024 23

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
      }
    ]
  }]

from vuex-i18n.

tikiatua avatar tikiatua commented on May 25, 2024 3

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();
  
});

from vuex-i18n.

kskrlin avatar kskrlin commented on May 25, 2024 3

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.

from vuex-i18n.

tikiatua avatar tikiatua commented on May 25, 2024 3

Hi everyone,

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

from vuex-i18n.

tikiatua avatar tikiatua commented on May 25, 2024 3

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

from vuex-i18n.

tikiatua avatar tikiatua commented on May 25, 2024 2

Hi @andrade1379,

I will add an example tomorrow.

from vuex-i18n.

kskrlin avatar kskrlin commented on May 25, 2024 2

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

from vuex-i18n.

akuma06 avatar akuma06 commented on May 25, 2024 2

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
    })
  })
})

from vuex-i18n.

tikiatua avatar tikiatua commented on May 25, 2024 2

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.

from vuex-i18n.

guins avatar guins commented on May 25, 2024 2

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
});

from vuex-i18n.

stalniy avatar stalniy commented on May 25, 2024 2

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

from vuex-i18n.

radek-altof avatar radek-altof commented on May 25, 2024 2

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 :)

from vuex-i18n.

kskrlin avatar kskrlin commented on May 25, 2024 1

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

from vuex-i18n.

narender2031 avatar narender2031 commented on May 25, 2024 1

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

from vuex-i18n.

adi3230 avatar adi3230 commented on May 25, 2024 1

@narender2031 It worked thanks

from vuex-i18n.

tikiatua avatar tikiatua commented on May 25, 2024

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.

from vuex-i18n.

 avatar commented on May 25, 2024

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

from vuex-i18n.

madebysoren avatar madebysoren commented on May 25, 2024

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

from vuex-i18n.

madebysoren avatar madebysoren commented on May 25, 2024

@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?

from vuex-i18n.

 avatar commented on May 25, 2024

@kikky7 Can you share?

from vuex-i18n.

BruDroid avatar BruDroid commented on May 25, 2024

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

+1

from vuex-i18n.

 avatar commented on May 25, 2024

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

from vuex-i18n.

stalniy avatar stalniy commented on May 25, 2024

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

from vuex-i18n.

stalniy avatar stalniy commented on May 25, 2024

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 :)

from vuex-i18n.

gomezmark avatar gomezmark commented on May 25, 2024

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
        }
      })
    }

from vuex-i18n.

brickgale avatar brickgale commented on May 25, 2024

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

from vuex-i18n.

 avatar commented on May 25, 2024

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?

from vuex-i18n.

CelticParser avatar CelticParser commented on May 25, 2024

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

from vuex-i18n.

narender2031 avatar narender2031 commented on May 25, 2024

I required my routes like this :-

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

@tikiatua any solution for this.

from vuex-i18n.

tikiatua avatar tikiatua commented on May 25, 2024

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.

from vuex-i18n.

adi3230 avatar adi3230 commented on May 25, 2024

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

from vuex-i18n.

michaelKaefer avatar michaelKaefer commented on May 25, 2024

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

from vuex-i18n.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.