vue.js - 如何 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
执行此操作的最佳实践方法是什么?
解决方案
:to="#"
被解释为'#
是一个变量名'。
尝试这个。
<router-link v-else to="#"></router-link>
或者<a>
直接使用。
<a v-else href="#"></a>