Cannot use v-for on stateful component root element because it renders multiple elements?

ofleaf picture ofleaf · May 26, 2017 · Viewed 27k times · Source

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?

Answer

Eric Guan picture Eric Guan · May 26, 2017

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