vue.js - 不能在 VueJS 中的有状态组件根元素上使用 v-for

标签 vue.js vuejs2

我正在尝试在 Vuejs 2.0 上构建小型应用程序,其中我有一个名为 Text.Vue 的组件文件,以下是组件:

<template>
    <!-- Post -->
    <div class="blog-item" v-for="item in items">

        <!-- Post Title -->
        <h2 class="blog-item-title font-alt"><a href="#">{{ item.title }}</a></h2>

        <!-- Author, Categories, Comments -->
        <div class="blog-item-data">
            <a href="#"><i class="fa fa-clock-o"></i> {{ item.created_at }} </a>
            <span class="separator">&nbsp;</span>
            <a href="#"><i class="fa fa-user"></i> John Doe</a>
            <span class="separator">&nbsp;</span>
            <i class="fa fa-folder-open"></i>
            <a href="">Design</a>, <a href="#">Branding</a>
            <span class="separator">&nbsp;</span>
            <a href="#"><i class="fa fa-comments"></i> 5 Comments</a>
        </div>

        <!-- Text Intro -->
        <div class="blog-item-body">
            <p>
                {{ item.content }}
            </p>
        </div>

        <!-- Read More Link -->
        <div class="blog-item-foot">
            <a href="#" class="btn btn-mod btn-round  btn-small">Read More <i class="fa fa-angle-right"></i></a>
        </div>

    </div>
    <!-- End Post -->
</template>

<script>
    export default {
        data() {
            return {
                title: 'POST WITH TEXT ONLY',
                contents: 'Suspendisse accumsan interdum tellus, eu imperdiet lacus consectetur sed. Aliquam in ligula ac lacus blandit commodo vel luctus quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras eu ultrices mauris.',
                date_time: '4 December',
                items: []
            }
        },
        beforeCreate() {
            axios.get('/Blog/api/posts').then(response => {
                if(response.status === 200)
                {
                    this.items = response.data.posts
                }
            })
        }
    }
</script>

在执行 npm run dev 或编译 Assets 文件时出现错误:

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

我不知道我哪里做错了,帮我解决这个问题。

谢谢

最佳答案

创建组件时需要1根元素,尝试将代码包装在 <div/> 中标签。它应该可以解决问题;

<div>
    <div class="blog-item" v-for="item in items">
        // Your code...
    </div>
</div>

关于vue.js - 不能在 VueJS 中的有状态组件根元素上使用 v-for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45565870/

相关文章:

javascript - 如何在 ES6 中的 Vue.js 中使用谷歌地图

laravel - 将 Laravel .env 变量添加到 Vue 组件

javascript - 计算 Vue 插槽的高度和宽度

css - Material 图标未在 vue 中导入

javascript - 我应该将多个 Vue.js 组件使用的通用实用函数放在哪里?

javascript - [vue-test-utils] : wrapper. setChecked() 必须传递一个 bool 值

javascript - Vuejs2:使用对象作为 Prop 时如何判断 Prop 更新?

javascript - Vue.js 与 Rails 不工作

javascript - vue2表单元素列表

vue.js - 为什么是:key attribute needed in vuejs v-for?