elementui将tooltip的内容,添加到指定的dom下

840 阅读1分钟

背景

  • tooltip组件,在显示弹出内容时,内容被挂载在body根节点下。
  • 挂载在body节点下,影响自定义组件的样式覆盖问题。

解决方法

<template>
    <div>
        <el-tooltip
                placement="top"
                :append-to-body="false" 
                content="ToolTip"
                ref="_toolTip">  <!--重点::append-to-body="false" -->
            <el-button>提示</el-button>
        </el-tooltip>

        <!-- 希望将tooltip的弹出部分内容的dom放在这里面 -->
        <div ref="toolTipLoad"></div>
    </div>
</template>

<script>
    export default {
        mounted() {
            // 在mounted的时候只需要使用这句话。
            this.$refs.toolTipLoad.appendChild(
                this.$refs._toolTip.popperVM.$el
            )
        }
    }
</script>

实现根据

tooltip是基于vue-popper扩展的,而vue-popper组件提供了appendToBody参数,它默认值是true,也就是默认就会把弹出的内容添加到body根节点。部分重要代码入下:

// vue-popper.js 的部分代码
  created() {
      this.appendedArrow = false;
      this.appendedToBody = false;
      this.popperOptions = Object.assign(this.popperOptions, this.options);
    },
    
createPopper() {
    this.$nextTick(() => {
      if (this.visibleArrow) {
        this.appendArrow(this.popper);
      }
       // 根据参数来决定是否要把弹出的内容显示添加到body根节点。
      if (this.appendToBody && !this.appendedToBody) {
        this.appendedToBody = true;
        document.body.appendChild(this.popper.parentElement);
      }