美文网首页
【ElementPlus】在v-for循环中使用el-toolt

【ElementPlus】在v-for循环中使用el-toolt

作者: Ringo_ | 来源:发表于2022-08-28 11:56 被阅读0次
悬浮显示背景色

在v-for循环中,如果给每一个循环元素都添加一个el-tooltip,感觉页面会变得非常卡顿,于是使用同一个el-tooltip,使多个元素触发这个el-tooltip,这个功能是在虚拟触发的基础上实现的。
创建测试数据,希望实现在鼠标指针在元素上悬浮时,显示该元素的背景色。
实现代码:

<template>
  <div class="box">
    <div
      v-for="(item, index) in data"
      :key="index"
      class="item"
      :style="{ background: `${item.color}` }"
      @mouseover="changeHoverEle(item, $event)"
      @mouseleave="visible = false"
    ></div>
  </div>
  <el-tooltip ref="tooltipRef" v-model:visible="visible" :virtual-ref="buttonRef" virtual-triggering>
    <template #content>
      <span>{{ color }}</span>
    </template>
  </el-tooltip>
</template>

<script setup lang="ts">
import { Ref, ref } from "vue";
let data: { id: number; color: string }[] = [];
// 测试数据,做500次循环,随机生成背景颜色
for (let i = 0; i < 500; i++) {
  data.push({
    id: i,
    color: `#${Math.floor(Math.random() * 0xffffff)
      .toString(16)
      .padEnd(6, "0")}`,
  });
}
const visible = ref(false);  //控制tooltip显示或隐藏
const tooltipRef: Ref<HTMLElement | null> = ref(null);
const buttonRef: Ref<HTMLElement | null> = ref(null);  //鼠标选中的元素
const color = ref();
const changeHoverEle = (item: { id: number; color: string }, e: any) => {
  buttonRef.value = e.currentTarget;
  color.value = item.color;
  visible.value = true;
};
</script>

<style>
.box {
  display: flex;
  margin-top: 100px;
}
.item {
  width: 10px;
  height: 10px;
  cursor: pointer;
}
</style>

相关文章

网友评论

      本文标题:【ElementPlus】在v-for循环中使用el-toolt

      本文链接:https://www.haomeiwen.com/subject/hgihnrtx.html