【问题标题】:How to v-if the router-link :to prop when value is null?如何 v-if 路由器链接:当值为空时支持?
【发布时间】: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


    【解决方案1】:

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

    试试这个。

    &lt;router-link v-else to="#"&gt;&lt;/router-link&gt;

    或者直接使用&lt;a&gt;

    &lt;a v-else href="#"&gt;&lt;/a&gt;

    【讨论】:

      【解决方案2】:

      您可以使用动态组件轻松做到这一点:

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

      【讨论】:

      • 这很有趣,谢谢。但是我如何将我的内容放在这个组件中,例如&lt;img&gt; 标签等
      • 您将把您的内容放在&lt;component&gt;...&lt;/component&gt;中的三个点的位置
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2011-09-25
      • 2018-02-04
      • 2021-09-20
      • 2020-06-17
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多