Vue3文字提示(Tooltip)

简介: 这是一篇关于 Vue2 文字提示(Tooltip)组件的教程,支持多种自定义属性,如最大宽度、展示文本、提示文本、样式、背景色、箭头显示等,并提供了在线预览示例。组件通过监听插槽和 `requestAnimationFrame` 实现了延迟显示与隐藏效果。文章详细介绍了组件实现代码及在页面中的使用方法。

可自定义设置以下属性:

  • 弹出提示最大宽度(maxWidth),类型:string | number,单位 px,默认 120

  • 展示的文本(content),类型:string | slot,默认 undefined

  • 弹出提示文本(tooltip),类型:string | slot,undefined

  • 设置弹出提示的样式(tooltipStyle),类型:CSSProperties,默认 {}

  • 弹出提示框背景颜色(bgColor),类型:string,默认 'rgba(0, 0, 0, 0.85)'

  • 是否显示箭头(arrow),类型:boolean,默认 true

  • 弹出提示触发方式(trigger),类型:'hover' | 'click',默认 'hover'

  • 弹出提示显示的延迟时间(showDelay),类型:number,单位 ms,默认 100

  • 弹出提示隐藏的延迟时间(hideDelay),类型:number,单位 ms,默认 100

  • 弹出提示是否显示(show),类型:boolean,默认 false

效果如下图: 在线预览

①创建提示框组件Tooltip.vue:

<script setup lang="ts">
import { ref, watch, watchEffect, computed } from 'vue'
import type { CSSProperties } from 'vue'
import { useSlotsExist, rafTimeout, cancelRaf } from '../utils'
interface Props {
  maxWidth?: string | number // 弹出提示最大宽度,单位 px
  content?: string // 展示的文本 string | slot
  tooltip?: string // 弹出提示文本 string | slot
  tooltipStyle?: CSSProperties // 设置弹出提示的样式
  bgColor?: string // 弹出提示框背景颜色
  arrow?: boolean // 是否显示箭头
  trigger?: 'hover' | 'click' // 弹出提示触发方式
  showDelay?: number // 弹出提示显示的延迟时间,单位 ms
  hideDelay?: number // 弹出提示隐藏的延迟时间,单位 ms
  show?: boolean // (v-model) 弹出提示是否显示
}
const props = withDefaults(defineProps<Props>(), {
  maxWidth: 120,
  content: undefined,
  tooltip: undefined,
  tooltipStyle: () => ({}),
  bgColor: 'rgba(0, 0, 0, 0.85)',
  arrow: true,
  trigger: 'hover',
  showDelay: 100,
  hideDelay: 100,
  show: false
})
const visible = ref(false)
const hideTimer = ref()
const top = ref(0) // 提示框 top 定位
const left = ref(0) // 提示框 left 定位
const contentRef = ref() // 声明一个同名的模板引用
const tooltipRef = ref() // 声明一个同名的模板引用
const activeBlur = ref(false) // 是否激活 blur 事件
const emits = defineEmits(['update:show', 'openChange'])
const slotsExist = useSlotsExist(['tooltip'])
const tooltipMaxWidth = computed(() => {
  if (typeof props.maxWidth === 'number') {
    return props.maxWidth + 'px'
  }
  return props.maxWidth
})
const showTooltip = computed(() => {
  return slotsExist.tooltip || props.tooltip
})
watch(
  tooltipMaxWidth,
  () => {
    getPosition()
  },
  {
    flush: 'post'
  }
)
watchEffect(() => {
  visible.value = props.show
})
function getPosition() {
  const contentWidth = contentRef.value.offsetWidth // 展示文本宽度
  const tooltipWidth = tooltipRef.value.offsetWidth // 提示文本宽度
  const tooltipHeight = tooltipRef.value.offsetHeight // 提示文本高度
  top.value = tooltipHeight + (props.arrow ? 4 : 6)
  left.value = (tooltipWidth - contentWidth) / 2
}
function onShow() {
  hideTimer.value && cancelRaf(hideTimer.value)
  if (!visible.value) {
    getPosition()
    rafTimeout(() => {
      visible.value = true
      emits('update:show', true)
      emits('openChange', true)
    }, props.showDelay)
  }
}
function onHide(): void {
  hideTimer.value = rafTimeout(() => {
    visible.value = false
    emits('update:show', false)
    emits('openChange', false)
  }, props.hideDelay)
}
function toggleVisible() {
  if (!visible.value) {
    onShow()
  } else {
    onHide()
  }
}
function onEnter() {
  activeBlur.value = false
}
function onLeave() {
  activeBlur.value = true
  tooltipRef.value.focus()
}
function onBlur() {
  visible.value = false
  emits('update:show', false)
  emits('openChange', false)
}
</script>
<template>
  <div
    class="m-tooltip-wrap"
    @mouseenter="trigger === 'hover' ? onShow() : () => false"
    @mouseleave="trigger === 'hover' ? onHide() : () => false"
  >
    <div
      ref="tooltipRef"
      tabindex="1"
      class="m-tooltip-content"
      :class="{ 'tooltip-padding': arrow, 'tooltip-visible': visible && showTooltip }"
      :style="`max-width: ${tooltipMaxWidth}; --tooltip-background-color: ${bgColor}; transform-origin: 50% ${top}px; top: ${-top}px; left: ${-left}px;`"
      @blur="trigger === 'click' && activeBlur ? onBlur() : () => false"
      @mouseenter="trigger === 'hover' ? onShow() : () => false"
      @mouseleave="trigger === 'hover' ? onHide() : () => false"
    >
      <div class="m-tooltip" :style="tooltipStyle">
        <slot name="tooltip">{
  { tooltip }}</slot>
      </div>
      <div v-if="arrow" class="tooltip-arrow"></div>
    </div>
    <span
      ref="contentRef"
      @click="trigger === 'click' ? toggleVisible() : () => false"
      @mouseenter="trigger === 'click' && visible ? onEnter() : () => false"
      @mouseleave="trigger === 'click' && visible ? onLeave() : () => false"
    >
      <slot>{
  { content }}</slot>
    </span>
  </div>
</template>
<style lang="less" scoped>
.m-tooltip-wrap {
  position: relative;
  display: inline-block;
  .m-tooltip-content {
    position: absolute;
    z-index: 999;
    width: max-content;
    pointer-events: none;
    transform: scale(0.8);
    opacity: 0;
    transition:
      transform 0.1s cubic-bezier(0.78, 0.14, 0.15, 0.86),
      opacity 0.1s cubic-bezier(0.78, 0.14, 0.15, 0.86);
    .m-tooltip {
      min-width: 32px;
      min-height: 32px;
      padding: 6px 8px;
      font-size: 14px;
      color: #fff;
      line-height: 1.5714285714285714;
      text-align: justify;
      text-decoration: none;
      word-break: break-all;
      background-color: var(--tooltip-background-color);
      border-radius: 6px;
      box-shadow:
        0 6px 16px 0 rgba(0, 0, 0, 0.08),
        0 3px 6px -4px rgba(0, 0, 0, 0.12),
        0 9px 28px 8px rgba(0, 0, 0, 0.05);
    }
    .tooltip-arrow {
      position: absolute;
      z-index: 9;
      left: 50%;
      bottom: 12px;
      transform: translateX(-50%) translateY(100%) rotate(180deg);
      display: block;
      pointer-events: none;
      width: 16px;
      height: 16px;
      overflow: hidden;
      &::before {
        position: absolute;
        bottom: 0;
        inset-inline-start: 0;
        width: 16px;
        height: 8px;
        background-color: var(--tooltip-background-color);
        clip-path: path(
          'M 0 8 A 4 4 0 0 0 2.82842712474619 6.82842712474619 L 6.585786437626905 3.0710678118654755 A 2 2 0 0 1 9.414213562373096 3.0710678118654755 L 13.17157287525381 6.82842712474619 A 4 4 0 0 0 16 8 Z'
        );
        content: '';
      }
      &::after {
        position: absolute;
        width: 8.970562748477143px;
        height: 8.970562748477143px;
        bottom: 0;
        inset-inline: 0;
        margin: auto;
        border-radius: 0 0 2px 0;
        transform: translateY(50%) rotate(-135deg);
        box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.1);
        z-index: 0;
        background: transparent;
        content: '';
      }
    }
  }
  .tooltip-padding {
    padding-bottom: 12px;
  }
  .tooltip-visible {
    pointer-events: auto;
    transform: scale(1);
    opacity: 1;
  }
}
</style>

②在要使用的页面引入:

<script setup lang="ts">
import Tooltip from './Tooltip.vue'
function openChange(visible: boolean) {
  console.log('visible:', visible)
}
</script>
<template>
  <div>
    <h1>{
  { $route.name }} {
  { $route.meta.title }}</h1>
    <h2 class="mt30 mb10">基本使用</h2>
    <Space>
      <Tooltip tooltip="Tesla" @open-change="openChange">
        <Button type="primary">特斯拉</Button>
      </Tooltip>
      <Tooltip tooltip="Godzilla" @open-change="openChange">
        <Button type="primary">哥斯拉</Button>
      </Tooltip>
    </Space>
    <h2 class="mt30 mb10">自定义样式</h2>
    <Tooltip
      :max-width="180"
      bg-color="#fff"
      :tooltip-style="{
        padding: '12px 18px',
        borderRadius: '12px',
        fontSize: '18px',
        color: '#1677ff'
      }"
    >
      <template #tooltip>Godzilla VS Kong</template>
      <Button type="primary">哥斯拉大战金刚</Button>
    </Tooltip>
    <h2 class="mt30 mb10">不同的触发方式</h2>
    <Space>
      <Tooltip>
        <template #tooltip>Vue Amazing UI</template>
        <Button type="primary">Hover Me</Button>
      </Tooltip>
      <Tooltip trigger="click">
        <template #tooltip>Vue Amazing UI</template>
        <Button type="primary">Click Me</Button>
      </Tooltip>
    </Space>
    <h2 class="mt30 mb10">延迟显示隐藏</h2>
    <Space>
      <Tooltip
        :show-delay="300"
        :hide-delay="300"
        tooltip="Vue Amazing UI (delay 300ms)"
        :tooltip-style="{ textAlign: 'center' }"
      >
        <Button type="primary">Delay 300ms Tooltip</Button>
      </Tooltip>
      <Tooltip
        :show-delay="500"
        :hide-delay="500"
        tooltip="Vue Amazing UI (delay 500ms)"
        :tooltip-style="{ textAlign: 'center' }"
      >
        <Button type="primary">Delay 500ms Tooltip</Button>
      </Tooltip>
    </Space>
    <h2 class="mt30 mb10">隐藏箭头</h2>
    <Tooltip :arrow="false" tooltip="Vue Amazing UI">
      <Button type="primary">Hide Arrow</Button>
    </Tooltip>
  </div>
</template>
相关文章
|
1月前
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
483 139
|
30天前
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
199 1
|
6月前
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
902 5
|
2月前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
359 11
|
1月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
239 0
|
3月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
420 1
|
3月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
234 0
|
4月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
135 0
|
6月前
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
578 17
|
7月前
|
JavaScript 前端开发 算法
Vue 3 和 Vue 2 的区别及优点
Vue 3 和 Vue 2 的区别及优点