【问题标题】:Vue - How to put Icon if src is emtpyVue - 如果 src 为空,如何放置图标
【发布时间】:2024-04-28 19:55:02
【问题描述】:

我有一个 Vue 项目,其中包含要在我的仪表板上显示的卡片组件。我有 4 张不同的卡片,我使用来自不同组件的道具发送它们的数据。这是我的卡片组件设计;

<div>
  <div>
    <div>
      <h5>{{ infoTitle }}</h5>
      <span :class="[infoResponsiveTextSize]">{{ infoText }}</span>
    </div>
    <div> 
      <div :class="[infoIconColor]">
        <img :src="infoLogoURL" class="logo" alt="" @error="$event.target.src='link/picture.png'"> 
      </div>    
    </div>
  </div>
  <p class="text-sm text-gray-500 mt-4">        
    <span class="mr-2" :class="[ infoSubIconColor ]">
      <i class="card-icons-mini">{{ infoSubIcon }}</i>
      <span>{{ infoSubText }}</span>
    </span>
    <span>{{ infoDescription }}</span>
  </p>
</div>

如你所见,有一堆道具。这是我使用它们的地方。

    <cardHeaderInfo 
      infoTitle = "Info Title" 
      infoText = "Info Text" 
      infoSubIcon = "material_icon_name" 
      infoSubIconColor = "Icon Color CSS class" 
      infoSubText = "Info Sub Text" 
      infoDescription = "Info Description" 
      infoIconColor = "Material Icon Background Color CSS Class"
      infoResponsiveTextSize = "Text Size CSS Class"
      infoDescriptionTextSize = "Descripotion CSS Class"
      infoLogoURL= ""
        />

所以这是我的问题。在这张卡片设计中,我想在 infoLogoURL 部分显示一个品牌的标志。我在这里留了空白,但是当我在那里放一些链接时,它完美地显示了徽标。顺便说一句,我还有另外三张这种卡片设计,我为它们使用了 Material Icon 图标,但这个有点特殊,所以我需要使用一些 .png 或 .svg 格式的标志。

假设在那个特定时刻,品牌徽标的链接不可用,我的项目无法访问 .SVG 文件。我想做的是在那一刻显示一个 Material Icon 图标。所以基本上如果infoLogoURL 道具中有一个链接,我想显示那个链接,标志。但是,如果该道具没有链接,我想激活不同的道具并显示一个图标而不是损坏的图像。我该怎么做?

【问题讨论】:

    标签: vue.js prop


    【解决方案1】:

    你可以使用 v-if 来做到这一点

    <div :class="[infoIconColor]">
            <img v-if="infoLogoURL !== ''" :src="infoLogoURL" class="logo" alt="" @error="$event.target.src='link/picture.png'"> 
            // v-else show your material icon
          </div>  
    

    【讨论】:

      【解决方案2】:

      使用conditional renderingv-ifv-else)测试图像是否存在并采取相应措施:

      <img v-if="infoLogoURL" :src="infoLogoURL" class="logo" alt="" />
      <md-icon v-else>{{ infoSubIcon }}</md-icon>
      

      如果定义了infoLogoURL,则显示&lt;img&gt;,否则显示&lt;md-icon&gt;

      【讨论】: