I have a Vue component that displays an image grid. I want users to be able to select an image by clicking on it. When an image is selected, its style should change, and if clicked again, it should return to its unselected state.
I am trying to bind the 'image-box-selected' class to a specific image, but I am facing some challenges. I cannot simply read a data attribute because that would cause all images to be selected simultaneously. Instead, I am using a selectedImages object as a dictionary for each imageId, where selectedImages['qhasdk'] will map to either false or true.
The problem I am encountering is that even though the selectedImages object is being generated and updated correctly, the 'image-box-selected' class never actually appears, even when the relevant key in selectedImages has been changed to true.
Vue.component('images-grid', {
props: ['env', 'images'],
data: function () {
return {
selectedImages: {}
}
},
methods: {
getSourceUrl: function (imageId) {
return getRootUrl() + '/image/' + this.env + '/' + imageId
},
updateSelectedImages: function (imageId) {
/* First we check we populated selectedImages with the IDs. */
if (Object.keys(this.selectedImages).length === 0) {
for (var i = 0; i < this.images.length; i++) {
this.selectedImages[this.images[i].id] = false;
}
}
this.selectedImages[imageId] = !this.selectedImages[imageId];
}
},
template: `
<div>
<img
v-for="image in images"
v-bind:id="image.id"
class="image-box image-box-selectable"
v-bind:class="{'image-box-selected': selectedImages[image.id]}"
v-bind:src="getSourceUrl(image.id)"
v-on:click="updateSelectedImages(image.id)">
</div>
`
})