Vue i18n - добавление локали к URL с использованием routerview - PullRequest
0 голосов
/ 27 июня 2018

Я использую сайт AspNetCore 2.1 в скафолде с VueJS, использующим TypeScript. Я пытаюсь интегрировать плагин kazupon i18n с видением маршрутизатора. Без интеграции URL-адреса работает нормально.

Я не могу получить правильные перенаправления, работающие как http://localhost/en/product и http://localhost/fr/product

Это начальный boot.ts, который использует VueI18n

import Vue from 'vue';
import VueRouter from 'vue-router';
import VueI18n from 'vue-i18n'

Vue.use(VueRouter);
Vue.use(VueI18n);

import { messages, defaultLocale } from './lang/i18n';

const i18n = new VueI18n({
    locale: defaultLocale,
    fallbackLocale: 'en',
    messages
})

const routes = [
        { path: '/', component: require('./components/home/home.vue.html') },
        { path: '/product', component: require('./components/product/product.vue.html') },
];

const router = new VueRouter({
    mode: 'history',
    routes: routes
});

new Vue({
    el: '#app-root',
    router: router,
    i18n: i18n,
    render: h => h(require('./components/app/app.vue.html'))
});

До сих пор я пробовал префикс routes, но это просто нарушает функциональность:

const routes = [{
    path: '/',
    redirect: `/${defaultLocale}`,
},
{
    path: '/:locale',
    children: [
        { path: '/', component: require('./components/home/home.vue.html') },
        { path: '/counter', component: require('./components/product/product.vue.html') },
    ]
}];

Я также пытался полагаться на router.beforeEach для установки локали.

router.beforeEach((to, from, next) => {
    let language = to.params.locale;
    if (!language) {
        language = 'en';
    }

    i18n.locale = language;
    next();
});

Это также не работает.

Я черпал вдохновение из github.com / ashour / vuejs-i18n-demo и vue-i18n-sap-multilingual-best-Practice , но кажется, что во время при переходе на i18n некоторые образцы могут быть устаревшими или утерянными, и эти варианты использования больше не работают.

Ответы [ 2 ]

0 голосов
/ 25 июля 2018

Большое спасибо @Julian Paolo Dayag, в моем вопросе было три проблемы с подходом:

  1. требуется перенаправление на "/" + defaultLocale + to.path
  2. дочерние маршруты не должны начинаться с /, они должны быть product вместо /product
  3. router.beforeEach... больше не нужен

Я получил этот код:

const routes = [
  {
    path: "/",
    redirect: `/${defaultLocale}`
  },
  {
    path: `/(fr|en)`,
    component: require("./components/app/routertemplate.vue.html"),
    children: [
      { path: "", component: require("./components/home/home.vue.html") },
      {
        path: "product",
        component: require("./components/product/product.vue.html")
      }
    ]
  },
  {
    path: "/(.*)",
    redirect: (to: any) => {
      return "/" + defaultLocale + to.path;
    }
  }
];
0 голосов
/ 25 июля 2018

В первую очередь вам нужно было указать опцию base в конструкторе vue-router.

Но сначала вам нужно извлечь локаль из URL:

let locale = window.location.pathname.replace(/^\/([^\/]+).*/i,'$1');

, а затем укажите base в конструкторе VueRouter:

const router = new VueRouter({
    ...
    base: (locale.trim().length && locale != "/") ? '/' + locale : undefined
    ...
});

и, что не менее важно, передайте локаль в ваш VueI18n конструктор:

const i18n = new VueI18n({
    locale: (locale.trim().length && locale != "/") ? locale : defaultLocale,
    fallbackLocale: 'en',
    messages
})

См. Обновленный пример:

import Vue from 'vue';
import VueRouter from 'vue-router';
import VueI18n from 'vue-i18n'

Vue.use(VueRouter);
Vue.use(VueI18n);

import { messages, defaultLocale } from './lang/i18n';

var locale = window.location.pathname.replace(/^\/([^\/]+).*/i,'$1');


const i18n = new VueI18n({
    locale: (locale.trim().length && locale != "/") ? locale : defaultLocale ,
    fallbackLocale: 'en',
    messages
})

const routes = [
        { path: '/', component: require('./components/home/home.vue.html') },
        { path: '/product', component: require('./components/product/product.vue.html') },
];

const router = new VueRouter({
    base: (locale.trim().length && locale != "/") ? '/' + locale : undefined,
    mode: 'history',
    routes: routes
});

new Vue({
    el: '#app-root',
    router: router,
    i18n: i18n,
    render: h => h(require('./components/app/app.vue.html'))
});
...