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 组件,它将在其中呈现一个链接。我已经删除了与问题无关的任何内容(即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>
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)
有什么想法可以实现我想要的吗?
更好、更干净的方法:
<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)
| 归档时间: |
|
| 查看次数: |
10319 次 |
| 最近记录: |