Shahriar
Shahriar

Reputation: 2380

Moving v-for to component template in Vue

This is my JS code:

Vue.component('card-stack', {
  props: ['course'],
  template: `
      <h3 class="course-card__title">
        {{ course.title }}
      </h3>
    `
})

new Vue({
  el: '#app',
  data: {
    courses: [
      { title: 'sometext' }
    ]
  }
})

and this is my HTML:

<div id="app">
  <card-stack v-for="x in courses" v-bind:course="x"></card-stack>
</div>

My question is, how can I move the v-for to the component template part? something like this:

Vue.component('card-stack', {
  props: ['list'],
  template: `
      <div v-for="course in list">
          <h3 class="course-card__title">
             {{ course.title }}
          </h3>
      </div>
    `
})

Upvotes: 1

Views: 82

Answers (1)

AlekseyHoffman
AlekseyHoffman

Reputation: 2694

It doesn't work because in Vue 2 you can only have 1 root HTML element in the template.

Since you have a loop, it renders multiple elements. All you need to do is just wrap your loop with a div so there's only 1 root element:

template: `
  <div>
    <div v-for="course in list">
      <h3 class="course-card__title">
        {{ course.title }}
      </h3>
    </div>
  </div>
`
<card-stack :list="list"></card-stack>

Upvotes: 2

Related Questions