I'm experimenting with an image slider and I want to streamline the process by uploading images to Firestore and storing them in an array to feed into the slider. I already have code for image uploads, but I'm facing a challenge. Instead of a single file input, I added three thinking I could save the image URLs in an array. However, only the first image is being uploaded and stored, while the rest are not.
How can I resolve this issue?
Importing Slider Images
<form @submit.prevent="handleSubmit">
<h4>Create New Content</h4>
<input type="text" required placeholder="Insert Title" v-model="sliderTitle">
<label>Choose Images for Your Slider</label>
<input type="file" @change="handleChange">
<input type="file" @change="handleChange">
<input type="file" @change="handleChange">
<div class="error">{{ fileError }}</div>
<button v-if="!isPending">Create</button>
<button v-else disabled>Saving...</button>
</form>
</template>
<script>
import { ref } from 'vue'
import useStorage from '@/composables/useStorage'
import sliderCollection from '@/composables/sliderCollection'
import { timestamp } from '@/firebase/config'
import { useRouter } from 'vue-router'
export default {
setup() {
const { filePath, url, uploadImage } = useStorage()
const { error, addDoc } = sliderCollection('slider')
const sliderTitle = ref('')
const file = ref(null)
const fileError = ref(null)
const isPending = ref(false)
const router = useRouter();
const handleSubmit = async () => {
if (file.value) {
isPending.value = true
await uploadImage(file.value)
await addDoc({
sliderTitle: sliderTitle.value,
imageUrl: [url.value],
filePath: filePath.value,
createdAt: timestamp()
})
isPending.value = false
if(!error.value) {
router.push({ name: "Home" })
}
}
}
// allowed file types
const types = ['image/png', 'image/jpeg']
const handleChange = (e) => {
const selected = e.target.files[0]
console.log(selected)
if (selected && types.includes(selected.type)) {
file.value = selected
fileError.value = null
} else {
file.value = null
fileError.value = 'Please select an image of the type JPG or PNG'
}
}
return {
sliderTitle,
handleSubmit,
handleChange,
fileError,
file,
isPending
}
}
}
</script>
The Slider Itself
<template>
<div v-for="content in slider" :key="content.id">
<img :src="content.imageUrl" />
</div>
</template>
<script>
const images = [];
export default {
props: ['slider'],
name: "ImageSlider",
data() {
return { index: 0, imageUrl: images[0] };
},
methods: {
next() {
this.index = (this.index + 1) % images.length;
this.imageUrl = images[this.index];
},
autoChangeSlide() {
setInterval(() => {
this.next();
}, 3000);
},
},
beforeMount() {
this.autoChangeSlide();
},
};
</script>