Open kskrlin opened 7 years ago
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.
Hello @tikiatua I just came across this and would love to have an example of how this can be done.
Hi @andrade1379,
I will add an example tomorrow.
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();
});
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
}
]
}]
If you have any ideas on how to approach this, I have some time to work a bit with this. Please let me know.
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.
@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?
@kikky7 Can you share?
@atilkan Yes, I will try in next 2 days, I am very busy these last weeks.
@kikky7 I'm also looking into this. An example would be very awesome.
+1
@tikiatua What was that comment? It is already in my mailbox though.
Hi everyone,
I deleted the comment as it was not helpful and insulting towards a commenter.
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.
The easy way to do it is to use translations as proposed by @madebysoren + full page reload
Hi! I think I would do something like this:
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
})
})
})
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 :)
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
}
})
}
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
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.
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?
Sure. The meetup is on November 15th. I will supply the link to the presentation just afterwards.
@tikiatua Are you still working on that patch? Plz say yes - LOL
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
});
I required my routes like this :-
domain.com/en/home
domain.com/fr/accueil
domain.com/dk/hjem
@tikiatua any solution for this.
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.
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
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
@narender2031 It worked thanks
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
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
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 :)
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?