不能在有状态组件根元素上使用 v-for 因为它呈现多个元素?

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

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

来自 chrome 控制台的错误日志

[Vue 警告]:不能在有状态组件根元素上使用 v-for,因为它呈现多个元素:

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

vue.js:525 [Vue 警告]:多个根节点 return 来自渲染函数。渲染函数应该 return 单个根节点。 (在组件中找到)

我应该如何修复代码?

您的模板必须有一个根元素。这只是一个你不能打破的规则。由于您正在创建 table,因此将 tbody 作为根元素是有意义的。

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

对于懒惰的人:Vue 将其上具有 v-for 循环的根元素解释为生成多个根级别元素(现代 JS 框架中的 nono)。

只需将您的模板包裹在多余的空白中 <div>