首页 > 建站教程 > 前端框架 >  vue3 Runtime directive used on component with non-element root node. The directives will not function as intended.正文

vue3 Runtime directive used on component with non-element root node. The directives will not function as intended.

我爱模板网在使用vue3开发项目,写了如下代码:

<el-popover placement="bottom" :width="400" trigger="click">
  <template #reference>
    <el-tooltip effect="dark" content="上传JSON" placement="top">
      <el-icon><Document :color="isActiveDrawName === 'GeoJson' ? 'green' : '#ccc'" /></el-icon>
    </el-tooltip>
  </template>
  <FileUpload url="/resource/oss/upload" :errorTips="null" :limit="1" :fileType="['geojson', 'json']" :fileSize="50" @success="uploadGeoJsonSuccess" ref="upload" />
</el-popover>


浏览器显示正常,但是老是报黄色警告:

vue3 Runtime directive used on component with non-element root node. The directives will not function as intended.


vue3


报这种错的原因有很多,这里只是其中一种情况:

  Element Plus 的 el-popover 和 el-tooltip 都是 “指令式组件”,底层都依赖 DOM 元素的位置计算:

    1、el-popover 需要 #reference 提供一个 “稳定的 DOM 元素” 作为触发锚点;

    2、在 #reference 里直接放 el-tooltip,而 el-tooltip 本身也需要一个触发元素(el-icon);

    3、el-icon 本质是 inline 元素,且没有明确的 DOM 容器,两层指令组件嵌套在 “无容器的 inline 元素” 上,Vue 无法判断指令该依附哪个 DOM 节点,最终抛出 “non-element root node” 错误。


解决方案:给 #reference 加 “独立 DOM 容器”

核心修复:在 el-popover 的 #reference 内,给 el-tooltip 包裹一个块级 div,让 el-popover 有明确的触发 DOM 元素,同时 el-tooltip 也能正常工作:

<el-popover placement="bottom" :width="400" trigger="click">
  <template #reference>
    <div>
      <el-tooltip effect="dark" content="上传JSON" placement="top">
        <el-icon><Document :color="isActiveDrawName === 'GeoJson' ? 'green' : '#ccc'" /></el-icon>
      </el-tooltip>
    </div>
  </template>
  <FileUpload url="/resource/oss/upload" :errorTips="null" :limit="1" :fileType="['geojson', 'json']" :fileSize="50" @success="uploadGeoJsonSuccess" ref="upload" />
</el-popover>

这样就不会报警告了。