<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 组件,它将呈现一个链接。我删除了与问题无关的任何内容(即
rel
、 target
、 class
等)。了解 - 我对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/