Image Handling in Vue 3
March 7, 2025 ยท AI Conversations
—
### **1. Storing and Displaying Static Images**
If you have images in your project folder and want to display them:
#### **Option 1: Place Images in the `public` Folder**
– Save the image in `public/images/`
– Access it directly using:
<img src="/images/example.jpg" alt="Example Image">
– This works because everything in the `public` folder is served as-is.
#### **Option 2: Store Images in `src/assets/` and Import in Vue**
– Save the image in `src/assets/`
– Use `import` or `require`:
<script setup>
import exampleImage from '@/assets/example.jpg';
</script>
<template>
<img :src="exampleImage" alt="Example Image">
</template>
– This method ensures that Webpack or Vite processes and optimizes the image.
—
### **2. Handling User-Uploaded Images**
If the image is selected by a user and should be displayed before upload:
#### **Example: File Input and Preview**
<script setup>
import { ref } from 'vue';
const imageUrl = ref(null);
const previewImage = (event) => {
const file = event.target.files[0];
if (file) {
imageUrl.value = URL.createObjectURL(file);
}
};
</script>
<template>
<input type="file" @change="previewImage" accept="image/*">
<img v-if="imageUrl" :src="imageUrl" alt="Preview Image">
</template>
– This uses `URL.createObjectURL(file)` to preview the image without uploading it.
—
### **3. Fetching Images from an API or Database**
If your images are stored on a server and fetched dynamically:
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
const imageUrl = ref('');
onMounted(async () => {
const response = await axios.get('https://example.com/api/image'); // Replace with actual API
imageUrl.value = response.data.image_url;
});
</script>
<template>
<img v-if="imageUrl" :src="imageUrl" alt="Fetched Image">
</template>
– The image URL is dynamically fetched from an API.
—
### **Which One to Use?**
– Use `public/` for static images that won't change.
– Use `src/assets/` if you want Webpack/Vite processing.
– Use `URL.createObjectURL(file)` for previews of uploaded images.
– Use an API call for images stored on a server.
Let me know if you need more details! ๐