I have a Vue.Js (version 3) app that I am making. It uses v-for
to loop through a list, and each item in the list appears on the page. I want a delete button to appear on hover for each item, and I can't just use refs because I don't know what the list will be ahead of time. Anyone able to help?
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>