Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to components in vue.js

I'm struggling to understand how to pass data between components in vue.js. I have read through the docs several times and looked at many vue related questions and tutorials, but I'm still not getting it.

To wrap my head around this, I am hoping for help completing a pretty simple example

  1. display a list of users in one component (done)
  2. send the user data to a new component when a link is clicked (done) - see update at bottom.
  3. edit user data and send it back to original component (haven't gotten this far)

Here is a fiddle, which fails on step two: https://jsfiddle.net/retrogradeMT/d1a8hps0/

I understand that I need to use props to pass data to the new component, but I'm not sure how to functionally do it. How do I bind the data to the new component?

HTML:

    <div id="page-content">        <router-view></router-view>      </div>   <template id="userBlock" >    <ul>      <li v-for="user in users">{{user.name}} - <a v-link="{ path: '/new' }"> Show new component</a>      </li>    </ul>  </template>    <template id="newtemp" :name ="{{user.name}}">     <form>       <label>Name: </label><input v-model="name">       <input type="submit" value="Submit">     </form>   </template> 

js for main component:

Vue.component('app-page', {   template: '#userBlock',    data: function() {     return{          users: []       }     },  ready: function () {     this.fetchUsers(); },  methods: {     fetchUsers: function(){         var users = [           {             id: 1,             name: 'tom'           },           {             id: 2,             name: 'brian'           },           {             id: 3,             name: 'sam'           },         ];          this.$set('users', users);      }     }   }) 

JS for second component:

Vue.component('newtemp', {   template: '#newtemp',   props: 'name',   data: function() {     return {         name: name,         }    }, }) 

UPDATE

Ok, I've got the second step figured out. Here is a new fiddle showing the progress: https://jsfiddle.net/retrogradeMT/9pffnmjp/

Because I'm using Vue-router, I don't use props to send the data to a new component. Instead, I need set params on the v-link and then use a transition hook to accept it.

V-link changes see named routes in vue-router docs:

<a v-link="{ name: 'new', params: { name: user.name }}"> Show new component</a> 

Then on the component, add data to the route options see transition hooks:

Vue.component('newtemp', {   template: '#newtemp',   route: {    data: function(transition) {         transition.next({             // saving the id which is passed in url             name: transition.to.params.name         });      }   },  data: function() {     return {         name:name,         }    }, }) 
like image 986
retrograde Avatar asked Dec 30 '15 17:12

retrograde


People also ask

How do you pass Props to Vue component?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.


2 Answers

-------------Following is applicable only to Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.


If you want to pass data from your html while you add a new component. That is done using props.

<my-component prop-name="value"></my-component> 

This prop value will be available to your component only if you add the prop name prop-name to your props attribute.


When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:

<my-parent>     <my-child-A></my-child-A>     <my-child-B></my-child-B> </my-parent> 

And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event:

this.$dispatch('event_name', data); 

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent:

events:{     'event_name' : function(data){         this.$broadcast('event_name', data);     }, 

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event:

events: {     'event_name' : function(data){         // Your code.      }, }, 

The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.


Decide what type of data communication you want, and choose appropriately.

like image 98
notANerdDev Avatar answered Sep 21 '22 10:09

notANerdDev


The best way to send data from a parent component to a child is using props.

Passing data from parent to child via props

  • Declare props (array or object) in the child
  • Pass it to the child via <child :name="variableOnParent">

See demo below:

Vue.component('child-comp', {   props: ['message'], // declare the props   template: '<p>At child-comp, using props in the template: {{ message }}</p>',   mounted: function () {     console.log('The props are also available in JS:', this.message);   } })  new Vue({   el: '#app',   data: {     variableAtParent: 'DATA FROM PARENT!'   } })
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>  <div id="app">   <p>At Parent: {{ variableAtParent }}<br>And is reactive (edit it) <input v-model="variableAtParent"></p>   <child-comp :message="variableAtParent"></child-comp> </div>
like image 22
acdcjunior Avatar answered Sep 22 '22 10:09

acdcjunior