You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中为v-for渲染的多div元素实现hover显示按钮

Vue3 实现v-for列表项独立悬停显示元素

场景1:同一时间仅显示一个悬停元素

这种场景下无需用数组,只需用单个变量跟踪当前悬停的项即可:

<template>
  <div class="item-list">
    <!-- 遍历列表项 -->
    <div 
      v-for="item in items" 
      :key="item.id"
      class="list-item"
      @mouseenter="handleHoverEnter(item.id)"
      @mouseleave="handleHoverLeave"
    >
      <span>{{ item.name }}</span>
      <!-- 仅当前项悬停时显示指定元素 -->
      <div class="hover-element" v-if="hoveredItemId === item.id">
        {{ item.name }}的悬停内容
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 模拟列表数据
const items = ref([
  { id: 1, name: '项目1' },
  { id: 2, name: '项目2' },
  { id: 3, name: '项目3' }
])

// 跟踪当前悬停的项ID
const hoveredItemId = ref(null)

const handleHoverEnter = (id) => {
  hoveredItemId.value = id
}

const handleHoverLeave = () => {
  hoveredItemId.value = null
}
</script>

<style scoped>
.list-item {
  padding: 10px;
  border: 1px solid #eee;
  margin: 5px 0;
  position: relative;
}

.hover-element {
  position: absolute;
  top: 100%;
  left: 0;
  padding: 8px;
  background: #fff;
  border: 1px solid #ddd;
  margin-top: 5px;
}
</style>

场景2:支持同时显示多个悬停元素

如果需要多个项同时悬停时都显示对应元素,才需要用到数组,注意正确添加/移除ID:

<template>
  <div class="item-list">
    <div 
      v-for="item in items" 
      :key="item.id"
      class="list-item"
      @mouseenter="handleMultiHoverEnter(item.id)"
      @mouseleave="handleMultiHoverLeave(item.id)"
    >
      <span>{{ item.name }}</span>
      <div class="hover-element" v-if="hoveredIds.includes(item.id)">
        {{ item.name }}的悬停内容
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const items = ref([
  { id: 1, name: '项目1' },
  { id: 2, name: '项目2' },
  { id: 3, name: '项目3' }
])

// 存储所有当前悬停的项ID
const hoveredIds = ref([])

const handleMultiHoverEnter = (id) => {
  // 避免重复添加
  if (!hoveredIds.value.includes(id)) {
    hoveredIds.value.push(id)
  }
}

const handleMultiHoverLeave = (id) => {
  // 找到索引并移除
  const index = hoveredIds.value.indexOf(id)
  if (index !== -1) {
    hoveredIds.value.splice(index, 1)
  }
}
</script>

<!-- 样式同场景1 -->

你之前数组方案无效的可能原因

  • 判断条件错误,比如用===直接比较数组和ID,而非用includes检查ID是否在数组内
  • 添加/移除ID时逻辑出错,比如重复添加或未正确删除目标ID
  • 未给v-for项设置唯一:key,导致Vue的DOM复用逻辑干扰了状态判断

内容的提问来源于stack exchange,提问作者Eli Sterken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 04:49:55