1

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?

3 Answers 3

11

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;
        }
Sign up to request clarification or add additional context in comments.

Comments

1

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> 

Comments

1
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;
 }

3 Comments

data() {} is just the shorthand version of data: function() {}
Yes. Now if you were using a style guide compare the main function of data to the methods.
Yes, that was more for consistency

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.