I am making an app with Vue.js (V3) and have a list of div's rendered using v-for
. How would I add a setprate event listener to each div, that will show an element when a user hovers over it with their mouse cursor?
I have tried using an array to store the currently hovered-over div, but this did not seem to work.
You can achieve this by using Vue's v-for directive along with @mouseover and @mouseleave events to track which item is being hovered.
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
class="list-item"
@mouseover="hoverIndex = index"
@mouseleave="hoverIndex = null"
>
{{ item }}
<button v-if="hoverIndex === index" @click="deleteItem(index)">Delete</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref(["Item 1", "Item 2", "Item 3"]);
const hoverIndex = ref(null);
const deleteItem = (index) => {
items.value.splice(index, 1);
};
</script>
<style scoped>
.list-item {
padding: 10px;
border: 1px solid #ccc;
margin: 5px;
position: relative;
display: flex;
justify-content: space-between;
}
button {
background-color: red;
color: white;
border: none;
cursor: pointer;
}
</style>