Answer the question
In order to leave comments, you need to log in
How to apply style only to specific element on mouse hover in v-for loop?
I have a
cycle that displays many blocks, the values of the blocks are taken from the
array
and apply to the hover
How can this be done?
At the moment, on hover, the class is applied to all blocks, no matter which block I hover over
<span
class="chars square" v-for="(square, index) in squares" :key="square"
@mouseover="chooseShipOnBoard(index, square)"
@mouseout="isShipHovered = false"
:class="{hover: isShipHovered}"
>{{ square}}
squares: [
'1', 'a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1', 'j1',
'2', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2', 'j2',
'3', 'a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3', 'j3',
],
isShipHovered: false,
methods: {
chooseShipOnBoard(index, square) {
this.isShipHovered = true;
}
}
.hover {
background-color: green;
}
Answer the question
In order to leave comments, you need to log in
Cut out the mouseover and mouseout handlers, dynamic class assignment, the isShipHovered property, and the chooseShipOnBoard method.
Replace .hover
with .square:hover
- everything, nothing else is needed. If it is possible to do something only through css - do it only through css.
UPD. Taken from the comments:
I needed to use it through the script, because then I will manipulate this chhoseShipOnBoard method, for example, add classes to neighboring blocks so that when hovering, not only the current block is highlighted, but also several nearby blocks
data: () => ({
hovered: null,
...
}),
methods: {
getClasses(index) {
return что-то, в зависимости от index и this.hovered;
},
},
<span
v-for="(n, i) in squares"
@mouseover="hovered = i"
@mouseout="hovered = null"
:class="getClasses(i)"
>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question