Vue js error: 组件模板应该只包含一个根元素

我不知道错误是什么,到目前为止,我正在通过控制台日志来检查在选择一个文件(用于上传)之后的更改。

当我运行 $ npm run watch时,会得到以下错误:

“ Webpack 正在监视文件... ..。

95% 的辐射

编译失败,出现1个错误
19:42:29

在./resources/asset/js/Component/File.vue 中出现错误

Vue 模板语法 错误:

组件模板应该只包含一个根元素 对多个元素使用 v-if,则使用 v-else-if 链接它们 取而代之。

@ ./resources/asset/js/Component/AvatarUpload.vue 5:2-181@ ./resources/asset/js/app.js@multi./resources/asset/js/app.js ./resources/asset/sass/app.scss”

我的档案

<template>
<div class="form-group">
<label for="avatar" class="control-label">Avatar</label>
<input type="file" v-on:change="fileChange" id="avatar">
<div class="help-block">
Help block here updated 4 🍸 ...
</div>
</div>


<div class="col-md-6">
<input type="hidden" name="avatar_id">
<img class="avatar" title="Current avatar">
</div>
</template>


<script>
export default{
methods: {
fileChange(){
console.log('Test of file input change')
}
}
}
</script>

对于如何解决这个问题有什么想法吗? 实际上错误是什么?

187309 次浏览

Note This answer only applies to version 2.x of Vue. Version 3 has lifted this restriction.

You have two root elements in your template.

<div class="form-group">
...
</div>
<div class="col-md-6">
...
</div>

And you need one.

<div>
<div class="form-group">
...
</div>


<div class="col-md-6">
...
</div>
</div>

Essentially in Vue you must have only one root element in your templates.

You need to wrap all the html into one single element.

<template>
<div>
<div class="form-group">
<label for="avatar" class="control-label">Avatar</label>
<input type="file" v-on:change="fileChange" id="avatar">
<div class="help-block">
Help block here updated 4 🍸 ...
</div>
</div>


<div class="col-md-6">
<input type="hidden" name="avatar_id">
<img class="avatar" title="Current avatar">
</div>
</div>


</template>


<script>
export default{
methods: {
fileChange(){
console.log('Test of file input change')
}
}
}
</script>

if, for any reasons, you don't want to add a wrapper (in my first case it was for <tr/> components), you can use a functionnal component.

Instead of having a single components/MyCompo.vue you will have few files in a components/MyCompo folder :

  • components/MyCompo/index.js
  • components/MyCompo/File.vue
  • components/MyCompo/Avatar.vue

With this structure, the way you call your component won't change.

components/MyCompo/index.js file content :

import File from './File';
import Avatar from './Avatar';


const commonSort=(a,b)=>b-a;


export default {
functional: true,
name: 'MyCompo',
props: [ 'someProp', 'plopProp' ],
render(createElement, context) {
return [
createElement( File, { props: Object.assign({light: true, sort: commonSort},context.props) } ),
createElement( Avatar, { props: Object.assign({light: false, sort: commonSort},context.props) } )
];
}
};

And if you have some function or data used in both templates, passed them as properties and that's it !

I let you imagine building list of components and so much features with this pattern.

For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/

But basically:

  • Currently, a VueJS template can contain only one root element (because of rendering issue)
  • In cases you really need to have two root elements because HTML structure does not allow you to create a wrapping parent element, you can use vue-fragment.

To install it:

npm install vue-fragment

To use it:

import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);


// or


import { Plugin } from 'vue-fragment';
Vue.use(Plugin);

Then, in your component:

<template>
<fragment>
<tr class="hola">
...
</tr>
<tr class="hello">
...
</tr>
</fragment>
</template>

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.

The right approach is

<template>
<div> <!-- The root -->
<p></p>
<p></p>
</div>
</template>

The wrong approach

<template> <!-- No root Element -->
<p></p>
<p></p>
</template>

Multi Root Components

The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.

As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.

Here is how you can create a simple functional component.

Vue.component('my-component', {
// you must set functional as true
functional: true,
// Props are optional
props: {
// ...
},
// To compensate for the lack of an instance,
// we are now provided a 2nd context argument.
render: function (createElement, context) {
// ...
}
})

Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.

<template>
<ul>
<NavBarRoutes :routes="persistentNavRoutes"/>
<NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
<NavBarRoutes v-else :routes="loggedOutNavRoutes" />
</ul>
</template>

Now if we take a look at NavBarRoutes template

<template>
<li
v-for="route in routes"
:key="route.name"
>
<router-link :to="route">
\{\{ route.title }}
</router-link>
</li>
</template>

We cant do some thing like this we will be violating single root component restriction

Make this component functional and use render

{
functional: true,
render(h, { props }) {
return props.routes.map(route =>
<li key={route.name}>
<router-link to={route}>
{route.title}
</router-link>
</li>
)
}

Here you have it you have created a multi root component, Happy coding

Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/

I was confused as I knew VueJS should only contain 1 root element and yet I was still getting this same "template syntax error Component template should contain exactly one root element..." error on an extremely simple component. Turns out I had just mispelled </template> as </tempate> and that was giving me this same error in a few files I copied and pasted. In summary, check your syntax for any mispellings in your component.

instead of using this

Vue.component('tabs', {
template: `
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>


<div class="tabs-content">
<slot></slot>
</div>
`,
});

you should use


Vue.component('tabs', {
template: `
<div>
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>


<div class="tabs-content">
<slot></slot>
</div>
</div>
`,
});


Just make sure that you have one root div and put everything inside this root

  <div class="root">
<!--and put all child here --!>
<div class='child1'></div>
<div class='child2'></div>
</div>

and so on

For vue 3 they removed this constraint in template syntax :

<template>
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
</template>

but it's still existing in JSX syntax :

Incorrect ❌

setup(props,{attrs}) {


return ()=>(
<header>...</header>
<main  {..attrs}>...</main>
<footer>...</footer>
)
}

Correct ✔

setup(props,{attrs}) {


return ()=>(
<>
<header>...</header>
<main  {..attrs}>...</main>
<footer>...</footer>
</>
)
}

In addition to Bert and blobmaster responses:

If you need to remove the root element from the DOM you can exploit css and use display: value on the root element.

Bit of a misleading error.

What fixed it on my side was the fact that I had an additional </div> without an opening <div>.

I spotted it using Find/Replace on "div" which gave an odd number.

Wrap everything in one div and it will resolve the issue. For example,

div

----div

----/div>

----div>

----/div>

/div

It is similar concept to React.js

I experienced this kind of issue and the issue was fixed by adding a main parent div tag or section if it is a section type of component.

<div class="list-of-friends">
<h3>Hello World</h3>
</div>