Vue: the parent template does not permit the use of v-for directives

Upon creating a simple post list component, I encountered an error when trying to utilize the v-for directive:

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

How can I go about iterating through and displaying each post?

To pass data from a Laravel backend as a prop to the component, I am using allBehaviourPosts like this:

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

My component:

<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>

Answer №1

Vue 2 requires each component to have a single root element, preventing conditional rendering or list rendering directly on the root. To work around this limitation, you can wrap your content in another element like a div, creating a new root:

<template>
  <div> <!-- single root element here -->

    <div v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id">
      <!-- ... -->
    </div>

  </div>
</template>

Additionally, Vue 2 does not support string interpolation in attribute bindings. Instead, use data bindings with the following syntax:

:ATTRIBUTE_NAME="VALUE"

For example, replace this:

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

with either of these solutions: using ES2015 template literals

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

or string concatenation:

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

Check out this Vue 2 demo for reference.

Note that Vue 3 allows multiple root nodes, enabling components to work with them directly. See an example here.

Answer №2

Recently, I encountered an error related to the template root not allowing 'v-for' directives. The solution to using directives in a template involves providing a root div to contain the element with the directives. I implemented this solution and it worked for me. For more information, you can refer to this link

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery's toggle function with a double click event to change the display to none

A div I created has the ability to expand to full screen upon double click, and I now wish to implement a toggle function so it can return to its original size when double clicked again. Initially, the code successfully increased the size of the div. Howe ...

Unusual shift in the modal's behavior occurs when the parent component's style.transform is applied

I have encountered an unusual issue with a modal's appearance and functionality. The modal is designed to enlarge images sent in a chat, with the chat upload preview div serving as the parent element and the modal as the child element. This strange be ...

Filling an HTML template with an $http response in VueJS

After learning about VueJs, I decided to embark on a small project - a nutrition app where food recommendations are made based on specific nutrients. Below is the JavaScript code snippet: recommendFood: function() { this.recs = {}; ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

Enhance the appearance of your custom Component in React Native by applying styles to Styled Components

I have a JavaScript file named button.js: import React from "react"; import styled from "styled-components"; const StyledButton = styled.TouchableOpacity` border: 1px solid #fff; border-radius: 10px; padding-horizontal: 10px; padding-vertical: 5p ...

AngularJS fetches the 'compiled HTML'

If I have this angularjs DOM structure <div ng-init="isRed = true" ng-class="{'red': isRed == true, 'black': isRed == false}"> ... content </div> How can I obtain the 'compiled' version of this on a cl ...

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...

Transferring the AJAX response into a JavaScript variable

New to AJAX and JS here. I am implementing an AJAX code that fetches data from a php service. I am trying to figure out how to store the returned data in a JavaScript variable, which I can then display on the UI. Below is my AJAX code snippet: <script ...

Is there a specific method for organizing cached buffer conversions in Node.js for optimal efficiency?

In a GitHub discussion, it was pointed out that the Map's .has method does not work with buffers because identical buffers are considered as distinct objects. This limitation became apparent when attempting to store buffer string conversions in a map ...

Navigate JSON Object - Prior Action

I am looking for a solution related to the following question/answer: How can I cycle through JSON objects one by one in AngularJS on click I need help with a function that displays the previous item from a JSON object. When the first item is selected, c ...

Error: You can't use the 'await' keyword in this context

I encountered a strange issue while using a CLI that reads the capacitor.config.ts file. Every time the CLI reads the file, it throws a "ReferenceError: await is not defined" error. Interestingly, I faced a similar error with Vite in the past but cannot ...

How can I use AngularJS orderBy to sort by a specific object's string property?

Is there a way to prioritize items in a task list based on both their date of addition and their listed priority? I've managed to sort the tasks by date, but I'm looking for a solution that will organize items with the 'HIGH' priority a ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Generate a fresh array using a current array comprising of objects

Greetings! I am facing a challenge with an array of objects like the one shown below: const data = [ {day: "Monday", to: "12.00", from: "15.00"}, {day: "Monday", to: "18.00", from: "22.00"}, {day: ...

Unsuccessful attempt at testing RequireJS in a straightforward manner

As a beginner in RequireJS, I am currently experimenting to gain some experience. My goal is to make require load basic Angular first and then manually bring in Angular UI Bootstrap. However, I am encountering an issue where UI Bootstrap complains that ang ...

How to Effortlessly Populate Cascading Dropdowns in ASP.Net MVC 5 using a Reusable

I am currently working on an ASP.Net MVC 5 application that has multiple edit pages. Each edit page consists of various input elements such as textboxes, checkboxes, and dropdowns. I want to implement a functionality where the values of one dropdown are ch ...

Using JavaScript: How to utilize Array.reduce within a function that also accepts arguments

let foo = 0; let bar = 0; const arr1 = [1, 2, 3, 4, 5]; const arr2 = [6, 7, 8, 9, 10]; function calculateSum(arr) { return arr.reduce((accum, val) => accum + val, 0); } foo = calculateSum(arr1); // Expect foo to equal 15 bar = calculateSum(arr2); ...

What is the best way to extract a JSON string from the login PHP response?

I am working on creating a basic website along with an Android application that both retrieve data from the same database. While I have no issues in dealing with Android, I am facing difficulty in handling JSON strings in HTML. How can I fetch the JSON res ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

Is there a way to modify the displayed value of json_encode() with jQuery?

I am using the json_encode() function to insert data into the database. How can I retrieve just the values of name_units from the units row in the database? This is how the output looks like in PHP code (generated by json_encode()): my_table=>units=& ...