lollercoaster
lollercoaster

Reputation: 16533

Nested component rendering & binding in Vue.JS

I'm learning Vue.js and trying to get nested component rendering working.

I've started with the below (codepen here):

	var buildingComponent = Vue.component('building', {
        template: '#building-component',
		name: 'building-component',
	})

	var roomComponent = Vue.component('room', {
        template: '#room-component',
		name: 'room-component',
		props: ['number'],
	})

	var componentApp = new Vue({
		el: "#components-example",
		data: {
			buildings: [
				{id: 1, name: "144 Orange St", occupants: 5, rooms: [
					{rid: 1, number: "122"},
					{rid: 2, number: "123"},
					{rid: 3, number: "144"},
				]},

				{id: 2, name: "92 Firth St", occupants: 6, rooms: [
					{rid: 4, number: "155"},
					{rid: 5, number: "344"},
					{rid: 6, number: "343"},
				]},

				{id: 3, name: "123 Main St", occupants: 2, rooms: [
					{rid: 7, number: "4324"},
					{rid: 8, number: "1244"},
				]},
			],
		},
	})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<!-- Components Example -->
<template id="building-component">
	<div>
		<span>Name: {{ bldg.name }}</span>
		<ul v-if="bldg.rooms">
			<room v-for="room in bldg.rooms" v-bind:room="room" number="room.number"></room>
		</ul>
	</div>
</template>

<template id="room-component">
	<div>
		<li>
			<span>Room {{ room.number }}</span>
		</li>
	</div>
</template>

<p>Components example!</p>
<div id="components-example">
	<ul>
		<li v-for="bldg in buildings" v-bind:bldg="bldg"></li>
	</ul>
</div>

I can't seem to get Vue.js to render properly - I'm a bit confused on what I'm supposed to v-bind and where.

I'd of course like whatever is rendered to be 100% reactive to changes to the underlying instance data attributes.

Any idea what I'm doing wrong?

Upvotes: 1

Views: 418

Answers (1)

CD..
CD..

Reputation: 74176

A few things were missing:

  • The components were missing the template property.
  • The building component was not in use, and the bldg property was missing.
  • The room component had a number property instead of room.

See a working example: http://codepen.io/anon/pen/bqNJVe

Upvotes: 1

Related Questions