Sometimes a simple looking task might not be so simple. There could be times where you want to prompt the user to select a few images from a source or gallery. While custom solutions work, more often than not, they might take away a lot of your development time. If you have been through such a phase, here’s a quick solution. We’re going to use a library called vue-select-image and I’ll show how to integrate it with your assets.
First things first, install the library in your Vue project using:
npm install vue-select-image --save
Then add the following code where you want your image selection functionality implemented:
<template>
<div>
<vue-select-image
:dataImages="dataImages"
@onselectimage="onSelectImage"
:is-multiple="true"
:selectedImages="initialSelected"
@onselectmultipleimage="onSelectMultipleImage"
>
</vue-select-image>
<div v-if="selectedImages.length > 0">
<div>{{ selectedImages.length }} images selected:</div>
<div v-for="(image, idx) in selectedImages" :key="idx">
{{ image.alt }}
</div>
</div>
</div>
</template>
<script>
import VueSelectImage from "vue-select-image";
import "vue-select-image/dist/vue-select-image.css";
export default {
name: "SelectImage",
data() {
return {
selectedImages: [],
initialSelected: [],
dataImages: [
{
id: "1",
src: "https://unsplash.it/150?random=1",
alt: "nightprogrammer.com image 1",
},
{
id: "2",
src: "https://unsplash.it/150?random=2",
alt: "nightprogrammer.com image 2",
},
{
id: "3",
src: "https://unsplash.it/150?random=3",
alt: "nightprogrammer.com image 3",
},
{
id: "4",
src: "https://unsplash.it/150?random=4",
alt: "nightprogrammer.com image 4",
},
{
id: "5",
src: "https://unsplash.it/150?random=5",
alt: "nightprogrammer.com image 5",
},
{
id: "6",
src: "https://unsplash.it/150?random=6",
alt: "nightprogrammer.com image 6",
},
],
};
},
methods: {
onSelectImage(img) {
alert(`Selected image: ${img.alt}`);
},
onSelectMultipleImage(images) {
this.selectedImages = images;
},
},
components: {
VueSelectImage,
},
};
</script>
Code language: HTML, XML (xml)
In the above code, the used variables and functions are:
selectedImages: I’ve created an array to store the list of selected images
initialSelected: This is where you can store some image objects by default (I haven’t stored any)
dataImages: Here you can keep the collection of images (you might fetch from over an API call)
onSelectImage(): It’d call this method when you select a single image
onSelectMultipleImage(): It’d call this method whenever you select multiple images. Here, I’ve only copied the selected images data to the selectedImages variable. You can do whatever action you want to perform here.
I’ve then checked and listed the image alt data separately (if and when at least one image is selected, as on line no 12).
You can find a working solution of the above in my repos here: