ajthinking
ajthinking

Reputation: 4558

Vue data property not reactive

Considering the code below, I can not make the active data property reactive. In this case I would like to show a div only on mouseover on an image.

<template>
    <div>
        <img @mouseover="showInfo" class="cursor-pointer w-full" :src="project.images[0].url" width="100%">
        <div v-show="active" class="bg-red h-12">
            Info about the image
        </div>
    </div>    
</template>

<script>
    export default {
        props: ['project'],
        data: function () {
            return {
                active: false
            }
        },
        methods: {
            showInfo: () => {
                this.active = !this.active;
            }
        }
    }
</script>

I have tried using v-if instead and printing active but to no effect. What am I doing wrong?

Upvotes: 1

Views: 9542

Answers (3)

Michael Mano
Michael Mano

Reputation: 3440

data() {
    return {
         active: false
     }
},


Update your data like the one above.

Also I'd rename your function to toggleInfo as it can also hide it on mouse out.

And remove the arrow.

toggleInfo() {
     this.active = !this.active;
 }

Upvotes: 1

Satyam Pathak
Satyam Pathak

Reputation: 6912

This can be simpler if you just change the value in HTML and you don't require a separate method for that.

@mouseover="active = !active"

It will look like this,

<div>
   <img @mouseover="active = !active" class="cursor-pointer w-full" :src="project.images[0].url" width="100%">
   <div v-show="active" class="bg-red h-12">
     Info about the image
   </div>
</div> 

Upvotes: 1

Fab
Fab

Reputation: 4657

Don't use arrow functions to define methods, this will not work.

Just replace

        showInfo: () => {
            this.active = !this.active;
        }

With:

        showInfo() {
            this.active = !this.active;
        }

Upvotes: 11

Related Questions