如何 v-if the router-link :to prop when value is null?

How to v-if the router-link :to prop when value is null?

我有一个 router-link 设置,其中 to 属性的 path 属性有时可能为空。然后在 vue-router 中导致错误,说它找不到 'indexOf' null.

我希望 router-link 仅在有可用的 non-null 值可供导航时呈现(显然)。如果值为 null,那么我不需要 link 存在,或者 link 可以作为占位符转到 #

这是router-link代码:

<router-link :to="{ path: Post.urlslug, name: 'PostView', params: {URLSlug: Post.urlslug} }">
   <!-- lots of images and text here with their own v-if statements -->
</router-link>

是否可以只在 :to 绑定上有一个条件语句,这样我就不必对整个 router-link 块进行大量复制和粘贴来实现 v-if 例如我宁愿避免这种情况:

 <router-link v-if="Post.urlslug != null && Post.urlslug.length" :to="{ path: Post.urlslug, name: 'PostView', params: {URLSlug: Post.urlslug} }">
       <!-- lots of images and text here with their own v-if statements -->
    </router-link>

 <router-link v-else :to="#"> <!-- <= this doesn't work anyway -->
       <!-- lots of images and text here with their own v-if statements -->
    </router-link>

以上代码不起作用,因为 # 不是 :to 属性可接受的值。执行此操作的最佳做​​法是什么?

:to="#" 被解释为“# 是一个变量名”。

试试这个。

<router-link v-else to="#"></router-link>

或直接使用<a>

<a v-else href="#"></a>

您可以使用动态组件轻松完成:

<component
  :is="Post.urlslug && Post.urlslug.length > 0 ? 'router-link' : 'a'" 
  :to="Post.urlslug && Post.urlslug.length > 0 ? { path: Post.urlslug, name: 'PostView', params: {URLSlug: Post.urlslug} } : undefined"
  :href="Post.urlslug && Post.urlslug.length > 0 ? undefined : '#'"
>