一、图片路径的处理

1. 使用相对路径

<img :src="imagePath" alt="Example Image">
const imagePath = './image.png';

2. 使用绝对路径

对于静态资源或第三方库,通常需要使用绝对路径。例如:

<img :src="imagePath" alt="Example Image">
const imagePath = '/static/image.png';

3. 使用require引入

<img :src="imagePath" alt="Example Image">
const imagePath = require('./image.png');

二、响应式数据绑定

<template>
  <div>
    <img :src="imageSrc" alt="Dynamic Image">
    <button @click="changeImage">Change Image</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const imageSrc = ref('./image1.jpg');

function changeImage() {
  if (imageSrc.value === './image1.jpg') {
    imageSrc.value = './image2.jpg';
  } else {
    imageSrc.value = './image1.jpg';
  }
}
</script>

在上面的例子中,imageSrc是一个响应式引用,它的值根据用户点击按钮时调用changeImage函数而改变。

三、处理加载问题

1. 使用占位图

<img :src="imageSrc" alt="Dynamic Image" srcset="placeholder.png">

2. 监听图片加载事件

<img :src="imageSrc" @load="imageLoaded" @error="imageError" alt="Dynamic Image">
function imageLoaded() {
  console.log('Image loaded successfully.');
}

function imageError() {
  console.log('Image failed to load.');
}

3. 使用异步组件

const AsyncImage = defineAsyncComponent(() => import('./ImageComponent.vue'));

四、总结