Vue运行Hello World示例时出现template单根元素报错如何解决
问题场景
在Vue框架中编写示例程序时触发运行报错,报错信息如下:
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.
触发报错的原始代码:
<template> <h1>Il tuo oroscopo</h1> <h3>{{ msg }}</h3> </template> <script> export default { data() { return { msg: 'Hello World!' } } } </script> <style scoped></style>
报错原因
Vue 2 单文件组件的模板语法强制要求:<template>标签内必须存在且仅存在一个根级元素。当前模板下直接放置了<h1>、<h3>两个同级的根元素,不符合语法约束,因此抛出该错误。
修复方法
只需要在所有同级元素外层包裹一个唯一的父级容器作为根节点即可,根据使用的Vue版本可以选择两种写法:
- 兼容所有Vue版本的通用写法:用普通块级标签(比如
<div>)包裹所有子元素 - Vue 3 专属写法:用片段(Fragment)空标签
<>包裹,不会额外渲染多余的真实DOM节点
修复后代码(Vue2通用版本)
<template> <div> <h1>Il tuo oroscopo</h1> <h3>{{ msg }}</h3> </div> </template> <script> export default { data() { return { msg: 'Hello World!' } } } </script> <style scoped></style>
修复后代码(Vue3版本,无多余DOM节点)
<template> <> <h1>Il tuo oroscopo</h1> <h3>{{ msg }}</h3> </> </template> <script> export default { data() { return { msg: 'Hello World!' } } } </script> <style scoped></style>
内容的提问来源于stack exchange,提问作者Mariano
相关产品推荐
相关产品推荐

