..."> ..."/> ..."> ...">

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

laravel Vue.js

梅猿

2020-03-12

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

我应该如何修复代码?

第1224篇《无法对有状态组件根元素使用v-for,因为它会呈现多个元素?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
null 2020.03.12

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android