el-popover气泡宽度由内容撑起

0 阅读1分钟

前言

  • el-popover有个width属性,就算不填也有默认值150。想要让气泡内容撑起气泡宽度要特殊处理
  • 以下内容由Trae改造生成

方案

<template>
  <el-popover
    placement="top"
    :width="0"
    effect="light"
    popper-class="auto-fit-popover"
    v-model:visible="popoverShow"
  >
    <div class="chat-popover-options">
      <div
        class="ctrl-item"
        @click="fuc1()"
      >
        功能1
      </div>
    </div>
    <template #reference>
      <button @click="popoverShow = true"></button>
    </template>
  </el-popover>
</template>

<style>
.auto-fit-popover {
  min-width: unset !important;
  width: auto !important;
  white-space: nowrap;
}
</style>

实现原理

  • :width="0" :通过设置宽度为 0,让 Element Plus 的 popover 组件不使用默认的固定宽度
  • !important :使用 !important 来覆盖 Element Plus 的默认样式,确保我们的样式能够生效
  • white-space: nowrap; :确保内容不会换行,这样气泡框的宽度就会根据内容的实际宽度来调整