【问题标题】:Vue: the template root disallows v-for directivesVue:模板根目录不允许使用 v-for 指令
【发布时间】:2018-10-19 12:11:18
【问题描述】:

我正在尝试制作一个简单的帖子列表组件,我在其中使用 v-for 指令,但我看到以下错误:

"eslint-eslint: the template root disallows v-for directives"

我应该如何循环和呈现每个帖子?

我将 allBehaviourPosts 作为道具从 Laravel 后端传递给组件,如下所示:

<related-post-list :relatedBehaviourPost= {{ $relatedBehaviourPosts }}></>

我的组件:

<template>
<div class="sidebar_related_content_container" v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id" style="">
    <a class="sidebar_related_content_image" href="/conducta-canina/{{ relatedBehaviour.slug }}"  style="background-image:url('{{ behaviour.image }}');">
        <div class="black_gradient" style=""></div>
    </a>
    <div class="sidebar_related_content_text_container" style="">
        <span class="sidebar_related_content_text_title" style="">{{ behaviour.postcategory.name }}</span>
        <span class="sidebar_related_content_text_description" style="">{{ behaviour.title }}</span>
    </div>
</div>
</template>
<!--SCRIPTS-->
<script>
    export default {

        props: ['relatedBehaviourPosts'],

        data: function () {
            return {
                //data
            }
        },

        mounted() {
            console.log('Footer mounted.')
        }
    }
</script>
<!--STYLES-->
<style scoped>

</style>

【问题讨论】:

    标签: javascript loops templates vue.js vuejs2


    【解决方案1】:

    在 Vue 2 中,每个组件只能包含一个 single root element,这排除了根元素上的 conditional renderinglist rendering。您必须将列表包装在另一个元素中(例如,div),使其成为根:

    <template>
      <div> <!-- single root element here -->
    
        <div v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id">
          <!-- ... -->
        </div>
    
      </div>
    </template>
    

    另请注意 Vue 2 不支持属性绑定中的字符串插值,因此必须将其替换为这种语法的数据绑定:

    :ATTRIBUTE_NAME="VALUE"
    

    特别是替换这个:

    <a href="/conducta-canina/{{ behaviour.slug }}"
       style="background-image:url('{{ behaviour.image }}');"></a> <!-- DON'T DO THIS -->
    

    用这个(使用ES2015 template literals):

    <a :href="`/conducta-canina/${behaviour.slug}`"
       :style="`background-image:url('${behaviour.image}');`"></a>
    

    或者用这个(使用字符串连接):

    <a :href="'/conducta-canina/' + behaviour.slug"
       :style="'background-image:url(\'' + behaviour.image + '\');'"></a>
    

    Vue 2 demo

    请注意,Vue 3 允许多个根节点,因此您的组件模板将work there

    【讨论】:

      【解决方案2】:

      我以前有时会遇到这个错误,问题是模板根不允许'v-for'指令。在模板中使用指令的解决方案是,您需要提供一个根 div 来包含具有您的指令的元素。 这在我的情况下有效。在这里查看更多信息https://eslint.vuejs.org/rules/valid-template-root.html

      <template>
      <!-- place a root element -->
      <div>
       <div v-for='item in menu'>some items</div>
      </div>
      </template>
      

      【讨论】:

        猜你喜欢
        • 2021-10-22
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-27
        • 2019-12-06
        相关资源
        最近更新 更多