sourcecode

서버 데이터에서 Vue2 라우터 링크

copyscript 2022. 7. 31. 22:20
반응형

서버 데이터에서 Vue2 라우터 링크

서버에서 콘텐츠를 로드하는 Vue2 SPA 페이지가 있습니다.CMS의 클라이언트가 편집할 수 있습니다.

사용자가 상대 링크(예를 들어 /about-us)를 추가할 때 Vue가 이 링크를 선택하여 메뉴 링크(이미 /about-us 링크가 있음)로 취급해야 합니다.

그러나 콘텐츠에 추가된 /about-us에 대한 링크는 페이지 전체를 새로고침하므로 vue 루트로 선택되지 않습니다.

어떻게 라우터를 이러한 링크에 접속할 수 있을까요?

지금까지 한 것은 백엔드 응답의 내용을 변경하는 것입니다.

그래서 나는 근본적으로 변화하고 있다.

<a href="/about-us">Text</a>

안으로

<router-link :to="{ path: '/about-us'}">Text</router-link>

사용방법:

function parseVueLinks($value)
{
    $pattern = "/<a([^>]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}

여전히 운이 없다.

이것이 어떻게 가능한 걸까요?

링크 해석에 관한 문제가 아닌 것으로 알고 있다면, 이것으로 문제가 없을 것 같습니다.결과 HTML을 컴파일하여 Vue 라우터가 기동할 수 있도록 합니다.기능이 있습니다.Vue.compile다음과 같은 이점이 있습니다.

Vue.component('my-component', {
  template: '<div></div>',
  props: {
    html: String
  },
  mounted() {
    let { render, staticRenderFns } = Vue.compile(this.html);
    new Vue({ el: this.$el, render, staticRenderFns, router })
  }
});

이 컴포넌트에서는 프로펠러를 사용하여 임의의 HTML을 지정할 수 있습니다.html에 컴파일 됩니다.mounted컴포넌트 템플릿을 교체합니다.주의해 주세요.router전해지다new Vue()이것은 Vue 라우터에 대한 참조로, 모든 Vue 라우터는 Vue 라우터의<router-link>HTML 내의 태그를 해결할 수 있습니다.

이제 이 컴포넌트를 사용하여 다음과 같이 HTML을 컴파일할 수 있습니다.

<my-component :html="content"></my-component>

어디에var content = parseVueLinks('<a href="/about-us">Text</a>').

여기서 작업 예를 보실 수 있습니다.https://codepen.io/anon/pen/BmmjwV

교환용 regex는 좋은 것 같습니다만, 1개가 빠져 있습니다./실제로 테스트한 결과 다음과 같은 해석 결과가 나타납니다.

<a href="/about-us">Text</a>

출력:

<router-link :to="{ path: 'about-us'}">Text</router-link>

올바른 대신:

<router-link :to="{ path: '/about-us'}">Text</router-link>

(을 참조).about-us대신/about-us)

이것 좀 시도해 볼래?

function parseVueLinks($value)
{
    $pattern = "/<a([^>]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '/$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}

이를 위한 가장 간단한 regex 패턴은/<a href="([^>]*)">(.+)<\/a>/.

테스트 예:

console.clear() 

const parseVueLinks = ($value) => {
  const re = /<a href="([^>]*)">(.+)<\/a>/g;
  const matches = re.exec($value);
  return `<router-link :to="{ path: '${matches[1]}'}">${matches[2]}</router-link>`
}

console.log(parseVueLinks('<a href="/about-us">Text</a>'))
console.log(parseVueLinks('<a href="http://google.com">Goooooogle</a>'))


저는 PHP를 모릅니다만, 동등한 PHP는 다음과 같습니다(https://www.functions-online.com/preg_match.html):

function parseVueLinks($value)
{
  $pattern = "/<a href="([^>]*)">(.+)<\/a>/";
  $matches = [];
  preg_match($pattern, $replace, $matches);
  return "<router-link :to=\"{ path: '" + $matches[1] + "'}\">" + $matches[2] + "</router-link>"; 
}

이 존재하는지 궁금해요.http|https|mailto|telregex의 경우 링크에서 검증을 수행한다는 의미입니까?

사용 가능한 경우preg_match()두 번째 regex 스텝을 실행할 수 있습니다.$matches[1]출력 전.하나의 큰 정규식을 사용하는 것보다 두 번째 단계로 검증하는 것이 더 쉬워 보입니다.


다음 주석 편집

문제는 정규식에 없다.서버에서 꺼낸 콘텐츠를 구문 분석하지 않고 Vue에 있습니다.

서버 측 렌더링을 사용하는 경우에는 적용되지 않을 수 있지만, 내용에서 링크를 적용하는 방법은 다음과 같습니다.

My Component.ts

<template>
  <div class="row">
    ...
      <router-link :to="'/' + measure.link" class="measure">
        <i class="measure-icon fa fa-lg" :class="measure.icon" aria-hidden="true">
          <span class="title">{{measure.title}}</span>
        </i>
      </router-link>

서서,,measure는 서버에서 가져온 객체입니다.는 모든 것을 있다.<router-link>다이나믹 컴포넌트에서는 동작할 수 있습니다만, 그 요소가 오버킬이라고 생각됩니다.<router-link.

서버가 클릭에 404로 응답하는 경우에도 문제가 있을 경우 링크 앞에 #를 추가하여 해시 모드 라우팅(기본값)을 사용할 수 있습니다.#/about-us.

또는 Vue 라우터에서 이력 모드를 설정합니다.

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

를 위해서는 가 "Direct"로 .index.html404를 위해서요.HTML 이력 모드」를 참조해 주세요.

또한 Vue에서 404를 캐치올 루트로 처리해야 합니다.

const routes = [
  ...
  { path: '*', component: NotFoundComponent },
]

언급URL : https://stackoverflow.com/questions/47199512/vue2-router-link-from-server-data

반응형