效果预览
先看效果:
要实现这样的效果, 需要先引入 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 传入 HTML | string | — | — |
placement | Tooltip 的出现位置 | string | top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end | bottom |
effect | Tooltip 的主题 | string | dark/light | dark |
disabled | 是否禁用 Tooltip | boolean | — | false |
offset | 出现位置的偏移量 | number | — | 0 |
transition | 定义渐变动画 | string | — | el-fade-in-linear |
visible-arrow | 是否显示 Tooltip 箭头,更多参数可见Vue-popper | boolean | — | true |
popper-options | popper.js 的参数 | object | 参考 popper.js 文档 | { boundariesElement: 'body', gpuAcceleration: false } |
open-delay | 延迟出现,单位毫秒 | number | — | 0 |
manual | 手动控制模式,设置为 true 后,mouseenter 和 mouseleave 事件将不会生效 | boolean | — | false |
popper-class | 为 Tooltip 的 popper 添加类名 | string | — | — |
enterable | 鼠标是否可进入到 tooltip 中 | boolean | — | true |
hide-after | Tooltip 出现后自动隐藏延时,单位毫秒,为 0 则不会自动隐藏 | number | — | 0 |
tabindex | Tooltip 组件的 tabindex | number | — | 0 |
前三个属性较为常用(后面的我也不知道能不能用,这个表格的内容是由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
组件