效果预览

先看效果:

提示组件

要实现这样的效果, 需要先引入 tooltip 组件, 然后在需要的地方使用 tooltip 组件, 代码如下:

<el-tooltip ref="tooltip" class="item" effect="light" content="点击图标可查看地图" placement="top">
  <span>住址</span>
</el-tooltip>

由代码可知, tooltip 组件基于 element-ui 实现, 通过 content 属性设置提示内容, placement 属性设置提示框位置, effect 属性设置提示框主题, class 属性设置提示框样式, ref 属性设置组件引用

以上属性可选的值如下表格:

属性说明类型可选值默认值
content显示的内容,也可以通过 slot 传入 HTMLstring
placementTooltip 的出现位置stringtop/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-endbottom
effectTooltip 的主题stringdark/lightdark
disabled是否禁用 Tooltipbooleanfalse
offset出现位置的偏移量number0
transition定义渐变动画stringel-fade-in-linear
visible-arrow是否显示 Tooltip 箭头,更多参数可见Vue-popperbooleantrue
popper-optionspopper.js 的参数object参考 popper.js 文档{ boundariesElement: 'body', gpuAcceleration: false }
open-delay延迟出现,单位毫秒number0
manual手动控制模式,设置为 true 后,mouseenter 和 mouseleave 事件将不会生效booleanfalse
popper-class为 Tooltip 的 popper 添加类名string
enterable鼠标是否可进入到 tooltip 中booleantrue
hide-afterTooltip 出现后自动隐藏延时,单位毫秒,为 0 则不会自动隐藏number0
tabindexTooltip 组件的 tabindexnumber0

前三个属性较为常用(后面的我也不知道能不能用,这个表格的内容是由Copilot自动生成的)

使用方法

比如我们要在一个 el-table 的表格中, 为 住址 这一列添加提示, 代码如下:

<el-table-column prop="address" label="住址" width="200">
  <template #header>
    <el-tooltip ref="tooltip" class="item" effect="light" content="点击图标可查看地图" placement="top">
      <span>住址</span>
    </el-tooltip>
  </template>
  <template v-slot="{ row }">
    {{ row.address }}
  </template>
</el-table-column>

其中 #header 为表头的插槽, v-slot 为表格内容的插槽 为什么不可以用v-slot的方式来实现呢?

因为这样的话在本组件中, 无法获取到 tooltip 组件的引用, 也就无法通过 this.$refs.tooltip 来获取到 tooltip 组件的引用, 也就无法通过 this.$refs.tooltip.showPopper = true 来显示 tooltip 组件

这样就为 住址 这一列添加了提示

但是现在需要一进入页面, 提示就显示出来, 而不是鼠标移动到 住址 这一列时才显示, 代码如下:

在mounted钩子函数中添加如下代码:

setTimeout(() => {
  // 显示tooltip提示
  const tooltip = this.$refs.tooltip
  tooltip.showPopper = true
  // 5秒后隐藏tooltip提示
  setTimeout(() => {
    tooltip.showPopper = false
  }, 5000)
}, 500)

为什么要等待500毫秒后才显示呢? 因为如果不等待, 页面的渲染速度跟不上代码的执行速度, 会导致无法获取到 tooltip 组件的引用, 从而无法显示 tooltip 组件

Last Updated:
Contributors: 黄定鑫