The data from the method in the Vue.js component is not displaying as expected

Currently diving into Vue.JS (2) and exploring the world of components. My current challenge involves using a component within another component, grabbing data from a data method. Here's what I have so far:

HTML

<div id="root">

    <h1>Tasks</h1>

    <list></list>

</div>

JS

Vue.component('list', {

    template: '<task v-for="task in tasks">{{ task.task }}</task>',

    data: function()  {

        return {

            tasks: [

                {task: 'Go to the store', completed: false},
                {task: 'Go to the shop', completed: true},
                {task: 'Go to the mall', completed: true}
            ]

        };
    }

});


Vue.component('task', {

    template: '<li><slot></slot></li>'

});


new Vue({

    el: '#root'

});

The result is currently displaying only a blank screen. However, when I replace the data with a string within the task template, it does show the string. This indicates that the "task" component works inside the "list" component.

Vue.component('list', {

    template: '<task>Test</task>',


});


Vue.component('task', {

    template: '<li><slot></slot></li>'

});


new Vue({

    el: '#root'

});

It seems like there might be an issue with rendering data using the method/data. Despite attempting various approaches, I haven't been able to resolve it.

If you have any insights or solutions, your help would be greatly appreciated. Thank you!

Answer №1

It is noted in the documentation that components must have a single root node.

If you apply a v-for directly on the top-level element, it will cause repetition. Wrapping the element in a div solves this issue.

To workaround this limitation, one can create a custom render function.

Vue.component('my-list', {
  template: '<div><task v-for="task in tasks">{{ task.task }}</task></div>',
  data() {
    return {
      tasks: [{
          task: 'Go to the store',
          completed: false
        },
        {
          task: 'Go to the shop',
          completed: true
        },
        {
          task: 'Go to the mall',
          completed: true
        }
      ]
    };
  }
});

Vue.component('task', {
  template: '<li><slot></slot></li>'
});

new Vue({
  el: '#root'
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.min.js"></script>
<div id="root">
  <h1>Tasks</h1>
  <my-list></my-list>
</div>

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

What is the best way to direct users to the individual product page once they make a selection

On my main products page, I am fetching all the products from a local JSON file. interface productItem { id: number; name: string; image: string; price?: string; prices: { half: string; full: string; }; ...

Guide on installing React packages during runtime

My React project has a number of packages that need to be installed, but they take up a lot of disk space. I would like to install them only when necessary, after the user interacts with a specific component that requires these packages. Is there a way t ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Unravel intricate JSON data and display it in a Material-UI table

How to convert the complex JSON data provided below into a material-ui table similar to the example shown. Each row may contain either a single value or multiple rows in a single box. I have attempted to display the data in 2 columns only, but need help wi ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

Exposure to vulnerabilities in react-scripts

While working on my ReactJS app, I encountered a challenge related to vulnerability and security issues. The use of react-scripts library has highlighted numerous vulnerabilities in the latest version. Is it possible for me to directly update the depende ...

Error message: Act must be used when rendering components with React Testing Library

I am facing difficulty while using react-testing-library to test a toggle component. Upon clicking an icon (which is wrapped in a button component), I expect the text to switch from 'verified' to 'unverified'. Additionally, a function ...

What is the reason that server.js is always excluded from the Webpack build process?

I am currently utilizing Vue.js 3 for the front end of my application, while employing Node/Express for the back-end. My goal is to implement server side rendering, but I have encountered some challenges along the way. As far as I can tell, the client-sid ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

I wasn't able to use the arrow keys to focus on the select box in my table, but I had no problem focusing on all

I'm a novice in jQuery and I encountered a situation where I have select boxes and text fields within my table. I successfully implemented arrow key functionality (down for next, up for prev) for shifting focus to the field by assigning classes to eac ...

I am currently facing a challenge in animating my ng-show/ng-hide animation

This particular issue has been widely recognized and discussed multiple times in various forums. Despite the extensive search, I have not come across satisfactory solutions. var aniApp = angular.module("aniApp", []); aniApp.controller('mainCtrl&ap ...

Every time I click once, two unnecessary AJAX calls are triggered, and the DOM remains outdated until I manually refresh the page

Whenever I click on a span, it sends an ajax request to delete the clicked todo from the database. However, in the DOM, the item is not removed until I refresh the page. Here is my index.html file: <ul class="list"> </ul> I noticed ...

Issues encountered when updating values in MaterialUI's TextField using Formik

Within my React functional component, I utilize Formik for form management and MaterialUI V5.10 for styling. The form includes TextField elements and a Canvas element. I am encountering two issues... Despite setting initial values in Formik, the TextFiel ...

The significance of webpack and the "@" symbol in the URL() function

<img src='@/assets/image.jpg'> functions properly and is converted to /static/img/image.xxxxx.jpg. However, attempting to utilize it in CSS with background-image:url('@/assets/image.jpg'); does not yield the desired outcome. The U ...

What could possibly be causing my app to exhaust CPU resources on Mozilla Firefox?

I have created a unique game application for Facebook. Currently, the app is not optimized with AJAX technology, resulting in multiple server requests causing high CPU usage (specifically in Firefox) which slows down the overall performance of the app. Alt ...

When submitting, Redux objects are being submitted with empty values

Whenever I try to submit my form, the object is being submitted empty. This was confirmed using the redux dev-tool, where it shows that the object is empty upon submission. The expected behavior is for a card to appear on the DOM with the information enter ...

Prevent side menu from automatically hiding when clicking on the heading

My menu is set up with headings and subheadings. When I click on the headings, it expands to display the corresponding subheadings, but it automatically collapses when clicking on the headings. I want it to stay expanded when clicking on the headings. He ...

Is there a reason why angularJS doesn't provide the exact error location directly, opting instead to just offer a link to their website that provides a generic explanation?

Why does AngularJS not provide the specific error location directly, such as which file the error is in, instead of just giving a link to their website with a generic explanation? This makes debugging very challenging! Whenever there is an error, it becom ...

ways to change date format in a React.js application using JavaScript

<b>Choose Date and Time</b><br/> <DateTimeField onChange={this.clockevent} format={"x"}/> clockevent=(newDate)=>{ var dateVal ="/Date("+newDate+")/"; var date = new Date(parseFloat(dateVal.substr(6))); console.log( ...