Vue: An actually one root template is warned `should contain exactly one root element`

Created on 5 Nov 2016  路  6Comments  路  Source: vuejs/vue

Vue.js version

2.0.3

Reproduction Link

<div v-if="type===1"></div>
<div v-if="type===2"></div>
<div v-if="type===3"></div>
<div v-if="type===4"></div>
<div v-if="type===5"></div>

Steps to reproduce

What is Expected?

No warning, because it will generate at most one element.

What is actually happening?

Warning: Component template should contain exactly one root element

improvement

Most helpful comment

The problem here is that without code analysis of all your v-if expressions (in fact it's near impossible because it depends on your component's runtime state), there's no way to tell whether it will really return only one element.

You can get around this by either using a dynamic component (turning all conditional branches into components), or use a render function instead.

All 6 comments

This is not a bug,

@plantain-00 wrap the content within a div.

<div>
  <div v-if="type===1"></div>
  <div v-if="type===2"></div>
  <div v-if="type===3"></div>
  <div v-if="type===4"></div>
  <div v-if="type===5"></div>
</div>

@anishdcruz
I'm OK with closing this issue, if it is difficult.

Angular2 has one root rule too, but it doesn't ban:

<div *ngIf="type===1"></div>
<div *ngIf="type===2"></div>
<div *ngIf="type===3"></div>
<div *ngIf="type===4"></div>
<div *ngIf="type===5"></div>

reactjs can do it by other way like:

if (this.props.type === 1) {
  return <div>...</div>
}
if (this.props.type === 2) {
  return <div>...</div>
}
...

3878 issued a similar situation, and it is fixed now.

anyway, if it is difficult, or not considered as a bug, feel free to close this.

In this case, since there is no v-else, what if all v-if conditions are false?

The problem here is that without code analysis of all your v-if expressions (in fact it's near impossible because it depends on your component's runtime state), there's no way to tell whether it will really return only one element.

You can get around this by either using a dynamic component (turning all conditional branches into components), or use a render function instead.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bfis picture bfis  路  3Comments

aviggngyv picture aviggngyv  路  3Comments

loki0609 picture loki0609  路  3Comments

Jokcy picture Jokcy  路  3Comments

julianxhokaxhiu picture julianxhokaxhiu  路  3Comments