简体   繁体   中英

v-bind:class to an object value

One of my Vue component is an image grid. I want the user to be able to "select" an image by clicking on it. Once an image has been selected, its style should change; if clicked again, it comes back to be un-selected.

I need to bind the 'image-box-selected' to the specific image but I am failing to do so. I cannot simply read a data attribute, because otherwise all images would be selected at the same time. So instead I have a selectedImages obj which acts a dictionary for each imageId (so selectedImages['qhasdk'] will map to either false or true).

The following snippet doesn't raise any issue and the selectedImages is generated and updated correctly. The issue is that 'image-box-selected' never actually appears, even then the relevant key for 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>
    `
})

You shouldn't use selectedImages[image.id] to get value and selectedImages is a object. I think should write as follows

selectedImages->image.id

if it is too complex, you should use "methods" to return value

I prefer immutable method, assigning this.selectedImages to new object:

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];
  this.selectedImages = [...this.selectedImages] // ES6
  // this.selectedImages = JSON.parse(JSON.stringify(this.selectedImages)) // ES5
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM