首页 > 解决方案 > 如何 v-if 路由器链接:当值为空时支持?

问题描述

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

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

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

上面的代码不起作用,因为它不是prop#可接受的值。:to执行此操作的最佳实践方法是什么?

标签: vue.jsvuejs2vue-routervuejs3

解决方案


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

尝试这个。

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

或者<a>直接使用。

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


推荐阅读