Props


Passing data to components

We learned that every component instance has its own isolated scope. This brings a question of "how to pass data from the Vue instance to a component". The (one of many)answer is using "props". 

For transferring data from the parent(Vue instance or could be a Vue component) to the child component we use a property called "props". 

The "props" array defines the settable properties that are sent from outside the component. 

Lets register an example global component and set the props:

Vue.component('child-component', {
template: '<div>{{ message }}</div>',
props: ['message']
});

And then pass the "message" prop string while calling the component:

<child-component message="just an example string message"></child-component>

The name of the string you specify in the props array must be the same as what you pass. Otherwise, Vue wouldn't recognize it. 

In this example I hard-coded the "message" string. But what if we need to pass dynamic data? 


Passing dynamic data

To make the passed prop dynamic, we use a ":"(short for "v-bind:") symbol before the name. 

For example lets recreate previous example and this set the "message" inside the Vue instance and pass it dynamically: 

Vue.component('child', {
template: '<div>{{ message }}</div>',
props: ['message']
});

new Vue({
el: '#app',
data: {
message: 'just an example string message!'
}
});

This time I don't hard-code the "message" string, instead I pass the "message" that was initialized in the Vue instance:

<child-component :message="message"></child-component>

Notice that single letter ":" is telling Vue that we're passing a variable and not a string anymore. 


Comments: