Dominic
Dominic

Reputation: 510

VueJS: :class, condition with index

I'm creating a list of (thumbnail) 2 images, and @click each image should be expanded to max-width, by adding said class ('max-w-full') to the classes. The class is added by setting the array entry with the same index nr. as the image (imgclicked[0], imgclicked[1]) in the list to 1.

data:() {
    imgclicked=[0,0], //by default both are set to 'small'/not 'max-w-full'
},

the template part looks like this:

<template v-for="(image,index) in images>
    <a @click="zoomImgClicked(index)">
        <img :src="image.filename" :class={'max-w-full' : imgclicked[index]==1,'w-12' : imgclicked[index]==0}"> 
    </a> // using this.imgclicked[index] gives me the error 'this.imgclicked[0] is undefined'
</template>

on click the method zoomImgClicked() ist launched:

   zoomImgClicked: function(i){
        if(this.imgclicked[i]==0){
          this.imgclicked[i]=1
        }else{
          this.imgclicked[i]=0
        }
    },

But this is not working. If I open the vue console and change the values of imgclicked[0] manually from 0 to 1 it works (images ae being resized). Also I see the method doing it's work, when logging in the console, the values are changed from 0 to 1 and vice versa. But it's not reflected on the page @click.

Why is that?

Upvotes: 0

Views: 227

Answers (2)

Christian Carrillo
Christian Carrillo

Reputation: 2761

try with array syntax:

<img
  :src="image.filename"
  :class="[
    {
      'max-w-full': imgclicked[index]==1,
      'w-12': imgclicked[index]==0
    },
    'static class if need'
  ]"
>

Upvotes: 0

Decade Moon
Decade Moon

Reputation: 34286

Please read Change Detection Caveats in the Vue docs.

Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

You should use the $set method for this:

this.$set(this.imgclicked, i, 1)

Upvotes: 2

Related Questions