user61629 user61629 - 1 year ago 165
Javascript Question

Understanding component props in VueJS

I'm trying out vuejs by following along with the laracasts series of webcasts on this. In, Jeffery Way discusses custom components. I have the following code based on his screencast:

<div id="app">
<tasks list="tasks"></tasks>

<template id="tasks-template">
<li :class="{'completed' : task.c}" @click = "task.c = ! task.c" v-for ="task in tasks">{{task.t}}</li>



<script src=""></script>
<script type="text/javascript">

vue.component('tasks', {
template: '#tasks-template',

props:['list'] // why not props:['tasks'] ??


new Vue({
el: '#app',
data: {
tasks: [
{t: 'go to doctor', c: false},
{t: 'go to work', c: false},
{t: 'go to store', c: true}


In this he discusses setting the props as follows:


Why is it not

props:['tasks'] ?

In it states:

Every component instance has its own isolated scope. This means you cannot (and should not) directly reference parent data in a child component’s template. Data can be passed down to child components using props.A “prop” is a field on a component’s data that is expected to be passed down from its parent component. A child component needs to explicitly declare the props it expects to receive using the props option:

How does the component know to associate the tasks array with list? Also in this case I assume child = component and parent = the vue instance?

Answer Source

The property on your component is called list and the value passed to it is tasks.

Let's see this. First you have your main Vue instance attached (mounted) to the element with identifier #app. So this is your starting point.

<div id="app">
    <tasks list="tasks"></tasks>

inside of your div you have a <tasks> tag. That tag correspond to a child component, so

child = component and parent = the vue instance

Is correct. The <tasks> component is an extension of the Vue class, which has only a property declared like list. The important thing here are scopes. Notice that the list property belongs to the tasks components, and has no value in its declaration, and the value passed to it on the template (everything inside the #app div) belongs to the parent Vue instance (declared on the data of the Vue instance). So why don't props:['tasks']? Because the <tasks> component has no tasks data or property. if you actually declared the property like tasks, you would have to write your template as follows

<div id="app">
    <tasks tasks="tasks"></tasks>

that would be a litle confusing. So thats why the prop is list and because of the declaration list="tasks" is that the component know that the list property has the value of the parent tasks array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download