You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel-Vue项目中字符串值为null时如何用Vue实现图标隐藏

问题根因

  • v-if判断逻辑存在空值兼容问题:当tags为null/undefined时,直接访问length属性会抛出JS异常,导致v-if判断逻辑失效
  • 判断逻辑与实际渲染的数据源不一致:判断条件用的是$page.tenants.tags,但实际渲染的是tenant.tags,两者没有对应,自然无法按预期控制显隐

修复方案

1. 调整判断条件

使用可选链操作符做空值兼容,同时对齐数据源,将v-if条件修改为:
v-if="tenant?.tags?.length > 0"
如果你的项目环境不支持可选链语法,可以替换为兼容写法:
v-if="tenant.tags && tenant.tags.length > 0"

2. 简化冗余代码

v-if已经保证仅在tags有值时才渲染当前块,不需要再写三元表达式兜底空字符串,直接输出即可。

修正后完整代码

<td class="pl-24">
  <div v-if="tenant?.tags?.length > 0" class="flex items-center">
    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
      <path
        d="M9.16667 2.5L16.6667 10C17.0911 10.4745 17.0911 11.1922 16.6667 11.6667L11.6667 16.6667C11.1922 17.0911 10.4745 17.0911 10 16.6667L2.5 9.16667V5.83333C2.5 3.99238 3.99238 2.5 5.83333 2.5H9.16667"
        stroke="#52525B"
        stroke-width="1.25"
        stroke-linecap="round"
        stroke-linejoin="round"
      ></path>
      <circle cx="7.50004" cy="7.49967" r="1.66667" stroke="#52525B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"></circle>
    </svg>
    <p class="text-sm leading-none text-gray-600 ml-2">{{ tenant.tags }}</p>
  </div>
</td>

内容的提问来源于stack exchange,提问作者luigichi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:39:00