【发布时间】:2021-02-24 11:11:06
【问题描述】:
我有一个router-link 设置,其中to 属性的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>
上面的代码不起作用,因为# 不是:to 属性的可接受值。执行此操作的最佳做法是什么?
【问题讨论】:
标签: vue.js vuejs2 vue-router vuejs3