<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的理解是,About和About都将在DOM中呈现为About,其中的区别是版本将给链接提供SPA功能(即不加载新页面,而是动态呈现一个组件)。
预期 - 当type="internal"时,它将呈现版本。当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 href="/about">About</a>
实际 - 当 type="internal"
时,<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>
<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
? - Yom T.router-link
来链接内部和外部链接。对于外部链接,它似乎会在传递为属性的“link”前缀中加上localhost:8080
(或根URL是其他什么)。 - jackdomleo7