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

新手上路,请多包涵

应用程序.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: {}
})

布局.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 警告]:从渲染函数返回多个根节点。渲染函数应返回单个根节点。 (在组件中找到)

我应该如何修复代码?

原文由 ofleaf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 522
2 个回答

您的模板必须有一个根元素。这只是你不能打破的一条规则。由于您正在制作表格,因此将 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

原文由 Eric Guan 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

只需将模板包装在多余的空白中 <div> 。 👌

原文由 corysimmons 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题