Reputation: 1702
First question - How to create components in a loop?
In my Index.vue I have a loop
<div v-for="(image, id, index) in images" class="col-md-4">
<photo :src ="image.src" :symbolId="image.id" :photoId="image.photo_id" :index="index"></photo>
</div>
in my app.js i registered a component
Vue.component('photo',
require('./components/Photo.vue')
);
and in my Photo.vue
<template>
<img v-on:click="replaceImages()" :src="src" class="img-responsive image" :data-symbol-id="symbolId" :data-photo-id="photoId">
<input :name="index" :data-symbol-id="symbolId" :data-photo-id="photoId"
type="hidden" :value="src">
</template>
<script>
export default {
name: 'photo',
props: {
src: {
type : String,
required: true
},
symbolId: {
type: String,
required: true
},
photoId: {
type: Number,
required: true
},
index: {
type: Number,
required: true
}
},
}
</script>
but when npm compiling it, i get an error
Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.
Upvotes: 4
Views: 7765
Reputation: 34924
Add one div
instead template, Vue expect one root element which contain all template, template tag is omitted by vue if using as below example
<template>
<div>
<img v-on:click="replaceImages()" :src="src" class="img-responsive image" :data-symbol-id="symbolId" :data-photo-id="photoId">
<input :name="index" :data-symbol-id="symbolId" :data-photo-id="photoId"
type="hidden" :value="src">
</div>
</template>
var child = {
template : '<div>Child component</div>'
}
var app = new Vue({
el:"#app",
components:{
child
},
data:{
name:''
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.js"></script>
<div id="app">
<child></child>
</div>
Upvotes: 3