Vue 路由器 - 带有模板字符串中的链接

Vue router - with links in a template string

我从翻译 API 中导入了一些文本字符串。其中一些字符串包含 HTML - 也包含 link。其中一些 links 必须 link 到内部路由器 links。例如 some link。单击此 link 当然可以 - 但它会重新加载应用程序,而不是将 link 推送到 SPA 中。

让 imported/external links 表现得像 vue-router links 的最佳方法是什么?

如果您希望由 vue-router 处理点击而不是重新加载页面,您真的应该使用 <router-link> 呈现链接。

否则您可以拦截点击(通过委托)并手动导航到新路由:

<div @click="onClick">
  <!-- Render the HTML in here -->
  <a href="/foo/bar">Link</a>
</div>
onClick(e) {
  if (e.target.tagName === 'A') {
    e.preventDefault();

    // Manually navigate to the route
    this.$router.push(e.target.href);
  }
}

尽管这是一个老问题,但我 运行 昨天遇到了同样的问题,可能有助于将来参考。

尝试 回答的方式并没有解决我的问题,因为锚的 href 标签带有 window.location.origin.

所以如果我在 https://www.example.com/about and want to navigate to the homepage I was getting this URL https://www.example.com/about/https://www.example.com 这不是预期的结果。

所以我的解决方案是在我的模板字符串中传递一个数据属性:

const toHomepage = `<span data-href="/">Link to Homepage</span>`;

然后在我的组件中:

<p @click="linkTo" v-html="link"></p>

看到 v-html 指令将输出我的模板字符串。

linkTo(e) {
  if (e.target.dataset.href) {
    this.$router.push(e.target.dataset.href);
  }
}

基于 https://dennisreimann.de/articles/delegating-html-links-to-vue-router.html:

的 Decade 答案的更复杂版本
function onClick(event: MouseEvent) {
  let target = event.target as HTMLElement
  while (target && target.tagName !== 'A') {
    target = target.parentNode as HTMLElement
  }
  const href = (target as HTMLLinkElement).href
  if (target && target.matches("a:not([href*='://'])") && href) {
    const { altKey, ctrlKey, metaKey, shiftKey, button, defaultPrevented } = event
    if (metaKey || altKey || ctrlKey || shiftKey) { return }
    if (defaultPrevented) { return }
    if (button !== undefined && button !== 0) { return }
    if (target && target.getAttribute) {
      const linkTarget = target.getAttribute('target') as string
      if (/\b_blank\b/i.test(linkTarget)) return
    }
    const url = new URL(href)
    const to = url.pathname
    if (window.location.pathname !== to && event.preventDefault) {
      event.preventDefault()
      router.push(to)
  }
}