如何v-if router-link: prop当值为空?



我有一个router-link设置,其中toprop的path属性有时可能为空。然后在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>

以上代码不起作用,因为#不是:toprop的可接受值。做到这一点的最佳实践方法是什么?

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

<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 : '#'"
>

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

试试这个。

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

或者直接使用<a>

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

最新更新