[Vuejs]-VueJS – toggle background image of list item on hover

0👍

background: isHover 
        ? `url(${item.location_image.thumbnails.large.url})`
        : `url(${item.location_image.thumbnails.largeHover.url})`

The isHover above references the data property of the component.

Your mouseOver() and mouseLeave() methods are assigning a property also called isHover on this.item[index]. These are two completely different properties. Where are you getting this.item from? I don’t see any props or it being declared as a data attribute.

Edit

You could have a isHover property on the gridItem. Therefore instead of passing index as an argument into the mouse event methods you can actually pass item. Then just set item.isHover = true. On the style binding you can just check against item.isHover.

Which means you don’t need the “other” isHover data property on the component.

0👍

There are a few things to consider in your code, the isHover variable which is being used to change the background of your elements is a data property, but in your mouseOver and mouseLeave you are trying to change the isHover property from an element on an array called item which is not declared in the code you posted. Another thing to notice is that it is not necessary to return anything on your mouseOver and mouseLeave methods.

As I understand, the expected behavior of your code is to change the background color of the item you are hovering with your cursor. A couple of suggestions, you should use class binding instead of adding inline styles to your template elements, also you could pass the item instead of the index on your mouseover and mouseleave handlers. Another thing to mention is that I would only recommend doing this if for some reason you need the isHover property on your item for something else, otherwise you should just use CSS :hover to achieve this. I made a small demo so you can take a look on what you can do to make your code work: codepen

Edit

To change the image when hovering over an item you should be using the isHover property of that particular item instead of the component’s data property isHover which you are currently using to try to change the image url. I updated my codepen.

Leave a comment