我有一个router-link
设置,其中to
prop的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
prop的可接受值。做到这一点的最佳实践方法是什么?
您可以轻松地使用动态组件:
<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>