如何在 Vue 中根据链接是外部还是内部动态渲染 <router-link> 或 <a>?

jac*_*eo7 5 html hyperlink typescript vue.js vue-router

<template>
  <component
    :is="type === 'internal' ? 'router-link' : 'a'"
    :to="type === 'internal' ? link : null"
    :href="type !== 'internal' ? link : null"
  >
    <slot />
  </component>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";

@Component
export default class SiteLink extends Vue {
  @Prop({
    validator: (value: string) =>
      ["external", "internal"].includes(value)
  })
  private readonly type!: string;

  @Prop({ type: String })
  private readonly link!: string;
}
</script>
Run Code Online (Sandbox Code Playgroud)

上面是一个 Vue 组件,它将在其中呈现一个链接。我已经删除了与问题无关的任何内容(即reltargetclass等)。

理解- 我对 Vue Router 的理解是,<router-link to="/about">About</router-link><a href="/about">About</a>都会像<a href="/about">About</a>在 DOM 中一样渲染,不同之处在于<router-link>版本将为链接提供 SPA 功能(即不加载新页面,它动态渲染组件)。

预期- 当 时type="internal",它将呈现该<router-link>版本。当 时type="external",它将渲染<a>版本。

<site-link type="external" link="https://stackoverflow.com">Stack Overflow</site-link>

Will render

<a href="https://stackoverflow.com">Stack Overflow</a>
Run Code Online (Sandbox Code Playgroud)
<site-link type="internal" link="/about">About</site-link>

Will render

<router-link to="/about">About</router-link>

Which is then handle by VueRouter to render

<a href="/about">About</a>
Run Code Online (Sandbox Code Playgroud)

实际- 当 时type="internal", a<a>没有在 DOM 中呈现 href当 时type="external",它会按预期呈现。

<site-link type="external" link="https://stackoverflow.com">Stack Overflow</site-link>

Will render

<a href="https://stackoverflow.com">Stack Overflow</a>
Run Code Online (Sandbox Code Playgroud)
<site-link type="internal" link="/about">About</site-link>

Will render

<router-link to="/about">About</router-link>

Which is then handle by VueRouter to render

<a>About</a> <!-- Notice there is no href -->
Run Code Online (Sandbox Code Playgroud)

有什么想法可以实现我想要的吗?

Ale*_*tut 5

更好、更干净的方法:

  <router-link v-if="type === 'internal' :to="link">
    <slot />
  </router-link>
  <a v-else :ref="link"> <slot /> </a>
Run Code Online (Sandbox Code Playgroud)

您可以v-if在根元素中使用,这样它就可以解决您的问题

或者您可能只是错过了路径部分?

  <component
    :is="type === 'internal' ? 'router-link' : 'a'"
    :to="type === 'internal' ? { path: link } : null"
    :href="type !== 'internal' ? link : null"
  >
    <slot />
  </component>
Run Code Online (Sandbox Code Playgroud)


abo*_*021 1

官方文档包含现在如何执行此操作的示例。

他们的方法是创建一个处理外部链接的自定义模板。