31

app.js

var Users = {
    template: `
        <tr v-for="list in UsersData">
            <th>{{ list.idx }}</th>
            <td>{{ list.id }}</td>
        </tr>
    `,
    data: function () {
        return {
            UsersData //get data from query
        }
    }
}

var mainview = new Vue({
    el: "#mainview",
    components: {
        'users': Users
    },
    method: {}
})

layout.blade.php

<body>
    <div class="container">
        <aside>...</aside>
        <main id="mainview">
            @section('content')
            @show
        </mainview>
    </div>
</body>

index.blade.php

@extends('layout')
@section('content')
<table>
    <thead>
        <tr>
            <th>IDX</th>
            <th>ID</th>
        </tr>
    </thead>
    <tbody>
        <users></users>
    </tbody>
</table>
@endsection

ERROR LOG from chrome console

[Vue warn]: Cannot use v-for on stateful component root element because it renders multiple elements:

<tr v-for="list in UsersData">
    <th>{{ list.idx }}</th>
    <td>{{ list.id }}</td>
</tr> 

vue.js:525 [Vue warn]: Multiple root nodes returned from render function. Render function should return a single root node. (found in component )

How should I fix code?

ofleaf
  • 615
  • 1
  • 6
  • 18

3 Answers3

46

Your template has to have one root element. It's just one rule you cannot break. Since you're making a table, it would make sense to make tbody the root element.

var Users = {
    template: `
        <tbody>
            <tr v-for="list in UsersData">
                <th>{{ list.idx }}</th>
                <td>{{ list.id }}</td>
            </tr>
        </tbody>
    `,
    data: function () {
        return {
            UsersData //get data from query
        }
    }
}

index.blade.php

@extends('layout')
@section('content')
<table>
    <thead>
        <tr>
            <th>IDX</th>
            <th>ID</th>
        </tr>
    </thead>
    <users></users>
</table>
@endsection
Eric Guan
  • 15,474
  • 8
  • 50
  • 61
  • I cannot wrap my template into or because there is not the single loop in my cause but two, first one for special columns, another one for data columns. Wrapping everything into – Dmitriy Sintsov Apr 27 '18 at 12:52
37

For the lazy: Vue interprets the root element having a v-for loop on it as producing multiple root level elements (a nono in modern JS frameworks).

Just wrap your template in a superfluous blank <div>.

corysimmons
  • 7,296
  • 4
  • 57
  • 65
1

I struggled with this, until I realized you can just add a section tag over everything in template and then this error goes away. Example

//gives error 

<template> 
  <div classname="allFutures" v-for="(items, index) in arr">
      <Future title="Shee" />
    </div>
</template> 

    // do this instead

<template>
  <section id="main" class="main-alt">
    <div classname="allFutures" v-for="(items, index) in arr">
      <Future title="Shee" />
    </div>
  </section>
</template>
Jack Coetzer
  • 91
  • 1
  • 4