el-select 选中弹出el-tooltip
时间: 2025-01-23 22:50:50 浏览: 47
### 实现 `el-select` 组件选中时触发 `el-tooltip`
为了实现当用户选择 `el-select` 中的一个选项时,能够显示对应的 `el-tooltip` 提示信息,可以采用如下方法:
#### 方法一:通过监听 `change` 事件
可以在 `el-select` 上绑定一个 `@change` 事件处理器,在该处理函数内动态设置要展示的工具提示内容并控制其可见性。
```html
<template>
<div style="display:inline-block;">
<!-- Select Component -->
<el-select v-model="selectedValue" placeholder="请选择..." @change="handleSelectChange">
<el-option
v-for="(item,index) in options"
:key="index"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<!-- Tooltip Component -->
<el-tooltip effect="dark" placement="top-start" ref="tooltipRef">
<template #content>{{ tooltipContent }}</template>
<span></span> <!-- Empty span to act as the trigger element -->
</el-tooltip>
</div>
</template>
<script setup lang="ts">
import { ref, nextTick } from 'vue';
const selectedValue = ref('');
const tooltipContent = ref('');
let timeoutId;
// Options data for select component
const options = [
{
value: 'option1',
label: '黄金糕'
},
{
value: 'option2',
label: '双皮奶'
}
];
function handleSelectChange(value) {
const selectedItem = options.find(option => option.value === value);
if (selectedItem && selectedItem.label) {
// Set new content and show after a short delay.
tooltipContent.value = `${selectedItem.label} 的详细介绍`;
clearTimeout(timeoutId);
// Hide immediately before showing again with updated text.
hideTooltip();
setTimeout(() => {
showTooltip();
// Automatically close it after some time or when another selection is made.
timeoutId = window.setTimeout(hideTooltip, 3000);
}, 50);
}
}
async function showTooltip() {
await nextTick(); // Ensure DOM updates are completed first.
const instance = this.$refs.tooltipRef;
if (!instance || !instance.showPopper) return;
instance.showPopper();
}
function hideTooltip() {
const instance = this.$refs.tooltipRef;
if (!instance || !instance.hidePopper) return;
instance.hidePopper();
}
</script>
```
这种方法利用了 Vue 的响应式特性以及 `nextTick()` 来确保更新后的视图已经被渲染出来之后再操作 `el-tooltip` 的实例对象。这样做的好处是可以精确地控制何时何地显示或隐藏提示框[^1]。
另外一种更简单的方式是在每次更改时手动调用 `doLayout()` 或者直接修改样式来调整位置和状态,但这通常不如上述方式灵活且容易维护。
阅读全文
相关推荐


















