P
P
postya2020-07-11 10:20:11
Vue.js
postya, 2020-07-11 10:20:11

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


script:
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

1 answer(s)
0
0xD34F, 2020-07-11
@postya

Cut out the mouseover and mouseout handlers, dynamic class assignment, the isShipHovered property, and the chooseShipOnBoard method.
Replace .hoverwith .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

Then store the index of the element the user hovered over. Also make a method that will receive the index of the element and, depending on the current selection, return the classes that need to be assigned:
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)"
>

https://jsfiddle.net/arw16jtf/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question