0

I am new to Vue.JS (2) and I am trying to learn components now. I try to use a component in another component with data from a data method (I know you can't use the property Data in a component). My code now:

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'

});

this will return a white screen. If I remove the data, and just use a string in the task template it shows the string, so the component "task" is working in the component "list".

Vue.component('list', {

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


});


Vue.component('task', {

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

});


new Vue({

    el: '#root'

});

So it seems like there is something wrong with displaying the data to the view with the method/data. I've tried many things but I just can't get it right.

Any help would be great, thanks in advance

1 Answer 1

2

As documented here,

components must contain exactly one root node.

Putting a v-for on the top-level element makes it repeated. If you wrap that element in a div, it works.

It looks like you may get around that limitation if you want to write your own 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>

Sign up to request clarification or add additional context in comments.

2 Comments

If you install Vue Devtools, you will see this error pop up in your dev console when the page tries to render.
I knew about this.. have looked everywhere for the mistake in the code but didn't notice I forgot to include that. Must be tired :) Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.