Skip to content

v-spare 指令

介绍

v-spare 指令用于处理图片加载失败的场景。当图片加载失败时,会自动切换到指定的备用图片,提升用户体验。

基础用法

当不提供备用图片时,会使用默认的 SVG 图标:

默认SVG加载失败示例
查看代码
vue
<template>
  <div class="demo-container">
    <div class="demo-item">
      <img src="https://example.com/non-existent-image.jpg" v-spare alt="默认SVG加载失败示例" class="demo-image" />
    </div>
  </div>
</template>

<script setup>
import { vSpare } from '@cp-vuedir/core'
</script>

<style scoped>
.demo-container {
  padding: 20px;
  border: 1px solid var(--vp-c-divider);
  border-radius: 4px;
  background-color: var(--vp-c-bg);
}

.demo-item {
  text-align: center;
}

.demo-image {
  max-width: 20%;
  height: auto;
  border: 1px solid var(--vp-c-divider-light);
  border-radius: 4px;
}
</style>

使用网络图片作为备用图

当原始图片加载失败时,会自动切换到指定的网络备用图片:

网络图片加载失败示例
查看代码
vue
<template>
  <div class="demo-container">
    <div class="demo-item">
      <img
        src="https://example.com/non-existent-image.jpg"
        v-spare="'https://secure.gravatar.com/avatar/e89584fc717a92922689cb33ab29dd93'"
        alt="网络图片加载失败示例"
        class="demo-image"
      />
    </div>
  </div>
</template>

<script setup>
import { vSpare } from '@cp-vuedir/core'
</script>

<style scoped>
.demo-container {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.demo-item {
  text-align: center;
}

.demo-image {
  max-width: 20%;
  height: auto;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>

使用本地图片作为备用图

可以使用导入的本地图片作为备用图:

本地图片加载失败示例
查看代码
vue
<template>
  <div class="demo-container">
    <div class="demo-item">
      <img
        src="https://example.com/non-existent-image.jpg"
        v-spare="logo"
        alt="本地图片加载失败示例"
        class="demo-image"
      />
    </div>
  </div>
</template>

<script setup>
import { vSpare } from '@cp-vuedir/core'
import logo from '../../../public/logo.jpg'
</script>

<style scoped>
.demo-container {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.demo-item {
  text-align: center;
}

.demo-image {
  max-width: 20%;
  height: auto;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>

API

属性名说明类型是否必选默认值
value
备用图片的URL地址,如果不提供则使用默认的SVG图标
string
Svg

注意事项

注意

  • 指令的值必须是一个有效的图片 URL(本地路径或网络 URL)
  • 建议提供与原始图片尺寸相近的备用图片,以保持页面布局的一致性