vue3 封装一个Tooltip 文字提示组件

2024-01-09 06:20:55

效果图

?默认展示icon图标,悬浮展示文字

如果slot有内容则展示对应内容?

??

实现

用的是El-Tooltip组件

Element - The world's most popular Vue UI framework

组件代码

<script setup lang="ts">
import { Icon } from '@/components/Icon'
import { ElTooltip } from 'element-plus'
import { PropType } from 'vue'

type Position =
  | 'top'
  | 'top-start'
  | 'top-end'
  | 'bottom'
  | 'bottom-start'
  | 'bottom-end'
  | 'left'
  | 'left-start'
  | 'left-end'
  | 'right'
  | 'right-start'
  | 'right-end'

defineProps({
  title: {
    type: String,
    default: () => ''
  },
  // 针对kb表格提示
  isKbTable: {
    type: Boolean,
    default: false
  },
  mtop: {
    type: [Number, String],
    default: () => 0
  },
  ml: {
    type: [Number, String],
    default: () => 10
  },
  location: {
    type: String as () => Position,
    default: () => 'top'
  },
  disabled: {
    type: Boolean,
    default: () => false
  },
  visible: {
    type: Boolean as PropType<Nullable<boolean>>,
    default: () => null
  },
  effect: {
    type: String as PropType<'dark' | 'light' | 'customized'>,
    default: () => 'customized'
  }
})
</script>
<template>
  <ElTooltip
    class="box-item"
    :effect="effect"
    :content="title"
    :placement="location"
    :disabled="disabled"
    :visible="visible"
    raw-content
    :popper-class="`vn-tooltip ${isKbTable ? 'vn-tooltip--kbTable' : ''} ${
      effect === 'light' ? 'vn-tooltip--light' : ''
    }`"
  >
    <div
      :class="{ 'inline-block': !$slots.default }"
      :style="{ marginTop: `${mtop}px`, marginLeft: `${!$slots.default ? ml : 0}px` }"
    >
      <Icon class="tooltip-icon" v-if="!$slots.default" icon="svg-icon:v2-query" :size="20" />
      <slot></slot>
    </div>
  </ElTooltip>
</template>

<style lang="less">
.vn-tooltip--default-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.inline-block {
  display: inline-block;
}

.tooltip-icon {
  pointer-events: none !important;
  cursor: pointer;
}

/* 自定义背景样式 */
.el-popper.is-customized {
  padding: 6px 12px;
  background: #2f3b53;
}

.el-popper.is-customized .el-popper__arrow::before {
  right: 0;
  background: #2f3b53;
  border-radius: 3px 0;
}

.vn-tooltip {
  z-index: 9999999 !important;
  max-width: 300px !important;
  font-family: Arial-Regular, Arial, serif;
  font-size: 12px !important;
  font-weight: 400;
  line-height: 16px;
  color: white !important;
  border-radius: 8px !important;
}

.vn-tooltip--kbTable {
  bottom: -25px !important;
}

.vn-tooltip--light {
  color: #000000 !important;
}
</style>

使用方法

//展示默认的提示图标
<Tooltip :title="t('agentConsole.preferences.globalAskDesc')" />
//带有内容
<Tooltip :title="t(item.title)" location="right" effect="light">
  <div>
    //内容
  </div>
</Tooltip>

文章来源:https://blog.csdn.net/ZMJ_QQ/article/details/135469334
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。