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

标签 html typescript vue.js hyperlink 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>

上面是一个 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>

<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>

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

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

Will render

<a href="https://stackoverflow.com">Stack Overflow</a>

<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 -->

任何想法如何实现我想要的?

最佳答案

更好更清洁的方法:

  <router-link v-if="type === 'internal' :to="link">
    <slot />
  </router-link>
  <a v-else :ref="link"> <slot /> </a>

您可以使用 v-if在根元素中,所以它解决了你的情况

或者您可能只是错过了路径部分?
  <component
    :is="type === 'internal' ? 'router-link' : 'a'"
    :to="type === 'internal' ? { path: link } : null"
    :href="type !== 'internal' ? link : null"
  >
    <slot />
  </component>

关于html - 如何根据链接是外部链接还是内部链接在Vue中动态呈现<router-link>或<a>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60953094/

相关文章:

html - last-child 不工作也不显示在 devtool 的 css 元素中

html - 如何选择包装的 HTML 元素?

javascript - 运行基类函数的函数引用时 Angular 丢失上下文

javascript - 更改可观察值

javascript - Vuelidate requiredIf 不适用于复选框

javascript - VUE + 谷歌地图如何包含google api

javascript - 页面刷新时导航到另一个路由 vuejs

jquery - Google+1 在另一行而不是与其他社交图标内联。有任何想法吗?

html - 锁定文本框的宽度

typescript - 在 TypeScript 中引用 Vue.js 的类型定义