programing

Vue-Router 언어 기반 루트프리픽스

randomtip 2023. 1. 15. 12:52
반응형

Vue-Router 언어 기반 루트프리픽스

사용하고 있다prerender-spa-pluginVue 앱에서 더 나은 SEO를 얻을 수 있도록 특정 페이지를 미리 렌더링합니다.

제 목표는 현재 사용하고 있는 방식을 바꾸는 것입니다.Vue-i18nurl param을 기반으로 할 수 있습니다./lang. 예:/en/home또는/nl/home이것으로 언어에 따라 프리렌더 할 수 있을 것 같습니다.

모든 부모 루트에 옵션 파라미터를 추가하는 프리픽서 함수를 만들었습니다./:lang?여기 있습니다.

const withPrefix = (prefix: string, routes: RouteConfig[]): RouteConfig[] => routes.map((route): RouteConfig => {
  // Avoiding mutations
  const clonedRoute = { ...route };
  // Every route except for '/'
  if (clonedRoute.path !== '/') {
    clonedRoute.path = prefix + clonedRoute.path;
  }
  return clonedRoute;
});

Vue 템플릿에서는 다음을 사용하고 있습니다.

<router-link :to="`/account`">

그래서 다음 페이지리다이렉트를 조작하려고 합니다.langPARAM.

첫 번째 접근법

가장 논리적인 것은 (라우터 내부)beforeEach):

const { lang } = to.params;
const redirectTo = lang ? to.fullPath : `${fullToLang}${to.fullPath}`;
if (from.fullPath !== redirectTo) {
  next({ path: redirectTo });
} else {
  next();
}

하지만 끝없는 루프로 들어갑니다. 왜냐하면 from은 항상 같기 때문입니다.

두 번째 접근법

사용.Routerbase소유물.

import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld";
import Test from "./components/Test";

Vue.config.productionTip = false;

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  base: "/en",
  routes: [
    {
      path: ":lang?/",
      component: HelloWorld,
      beforeEnter: (to, from, next) => {
        console.log(1);
        next();
      }
    },
    {
      path: "/:lang?/nope",
      component: Test,
      beforeEnter: (to, from, next) => {
        console.log(2);
        next();
      }
    },
    {
      path: "/:lang?/*",
      beforeEnter: (to, from, next) => {
        console.log(to);
        next("/nope");
      }
    }
  ]
});

new Vue({
  render: h => h(App),
  router
}).$mount("#app");

또는 라이브: https://codesandbox.io/embed/vue-template-0bwr9

근데 왜 이게 리다이렉트되는지 모르겠어요./en/nope루트에서 URL을 찾을 수 없는 경우에만(마지막 케이스).더 나아가, 내가 새로운 것을 만들어야 할까?Router변경할 때마다 인스턴스(instance)base?

세 번째 접근법

래퍼 구성 요소:router-link주입:to에 기반을 둔this.$route.params.lang.

이렇게 하면 앱이 로드된 후 탐색할 수 있지만 처음 새로 고침/초기화할 때는 그렇지 않습니다.

그럼 이걸 어떻게 해결해야 하죠?

~솔루션~

네, 첫 번째 접근방식은 올바른 방법이었지만 라우터가 이 명령어를 사용하여 어떻게 동작하는지 이해하지 못했습니다.next그리고.redirects이 상태는, 다음의 조건을 체크하고 있을 것입니다.to가 아니다from.

const redirectTo = lang ? to.fullPath : `${fullToLang}${to.fullPath}`;
if (to.fullPath !== redirectTo) {
  // Change language at i18n
  loadLanguageAsync(toLang as Language);

  next({ path: redirectTo });

  return;
}

나는 당신이 무엇을 요청하는지 완전히 확신하지 못한다.현재 언어 매개 변수(../en/..)가 아직 없는 경우 탐색에 접두사를 붙여야 할 것 같습니다.

이 문제를 해결하려면beforeEach()후크 및 리다이렉트 기능이 없는 경우에만lang파라미터가 존재합니다.

const { lang } = to.params
if(!lang) {
  next({ path: redirectTo })
}
next()

만약 당신이 원하는 것이 아니라면 명확히 해주시면 제 답변을 수정해 드리겠습니다.

이런 거?새로운 경로가 시작된다고 가정합니다./[lang]/...

주의사항 - 라우팅 시 오류가 발생합니다. /:lang/bar -> /foo/bar

Vue.lang = 'en'
function beforeEnter(to, from, next){

  if ((new RegExp(`^/${Vue.lang}$`))
  .test(to.path) 
  || 
  (new RegExp(`^/${Vue.lang}/`))
  .test(to.path))
  {
    next();
  } else {
    
    next({path: `/${Vue.lang}${to.path}`})
  }
};
Vue.mixin({
  beforeRouteEnter: beforeEnter
})
const Foo = { template: '<div>foo - {{$route.path}}</div>' }
const Bar = { template: '<div>bar - {{$route.path}}</div>' }
const Root = { template: '<div>Root - {{$route.path}}</div>' }
const Invalid = { template: '<div>404</div>' }

const routes = [
  
  { path: '/:lang/foo', component: Foo },
  { path: '/:lang/bar', component: Bar },
  { path: '/:lang/*', component: Invalid },
  { path: '/:lang', name: 'Home', component: Root },
  // some weird issue that prevents beforeRouteEnter ? so redirect, but else next is needed
  { path: '/', redirect: to => `/${Vue.lang}`}
]

const router = new VueRouter({
  routes
})

new Vue({
  data(){
    return {
      pLang: Vue.lang,
    }
  },
  computed: {
    lang: {
      get(){
        return this.pLang
      },
      set(val){
        Vue.lang = val
        this.pLang = val
      }
    }
  },
  router,
}).$mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h1>Hello App!</h1>
  <p>
     {{lang}}
    <select v-model="lang">
      <option value="en">en</option>
      <option value="cn">cn</option>
    </select>
    <!-- use router-link component for navigation. -->
    <!-- specify the link by passing the `to` prop. -->
    <!-- `<router-link>` will be rendered as an `<a>` tag by default -->
    
    <router-link to="/">Root</router-link>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
    <router-link to="/foo/bar">Go to Foo/Bar - not defined</router-link>
  </p>
  <!-- route outlet -->
  <!-- component matched by the route will render here -->
  <router-view></router-view>
</div>

언급URL : https://stackoverflow.com/questions/57463140/vue-router-language-based-route-prefix

반응형