Vue报错Component template should contain exactly one root element解决指南
Vue "Component template should contain exactly one root element" 报错解决方案
开发VueJS组件时,你可能会在浏览器控制台(或JS代码校验工具输出)中遇到如下报错:
Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.
报错原因
VueJS组件模板仅允许包含唯一一个根节点。
错误写法示例
<template> <div class="hola"> <h1>{{ msg }}</h1> </div> <div class="hello"> <h1>{{ msg }}</h1> </div> </template>
正确基础写法示例
<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template>
常规修复方案
将所有HTML标签包裹在同一个父元素内即可,示例如下:
<template> <div> <div class="hola"> <h1>{{ msg }}</h1> </div> <div class="hello"> <h1>{{ msg }}</h1> </div> </div> </template>
特殊场景进阶解决方案
部分场景下新增额外父元素会破坏原有HTML结构,比如子组件模板需要替换父级HTML表格中的多个<tr>节点,此时常规方案不可用,错误示例如下:
<template> <tr class="hola"> ... </tr> <tr class="hello"> ... </tr> </template>
这种特殊场景下有两种解决方案:
- 使用函数式组件
- 使用Fragments(更推荐的方案)
Fragments可将多个子节点聚合在同一个父级下,渲染时不会向DOM添加额外节点,使用步骤如下:
- 安装vue-fragments依赖
npm install vue-fragments # 或使用yarn:yarn add vue-fragments
- 在VueJS初始化时引入插件
import { Plugin } from "vue-fragments"; Vue.use(Plugin);
- 组件模板中按如下方式使用
<template> <v-fragment> <tr class="hola"> ... </tr> <tr class="hello"> ... </tr> </v-fragment> </template>
内容的提问来源于stack exchange,提问作者user13534081
相关产品推荐
相关产品推荐

