ApplePie
ApplePie

Reputation: 1185

How do I pass object correctly to my vue component?

I am recently learning Vue and I have read documentation about Vue components. However, I still do not understand how I can pass data object to props and have it rendered in the component template.

Here is my jsfiddle link

Or see my code below.

Vue.component('greeting', {
  template: `<h1>{{index}}</h1>`,
  props: ['persons']
});

var vm = new Vue({
  el: '#app',
  data: {
    persons: {
      'Mike': 'Software Developer',
      'Nikita': 'Administrator Assistant'
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="app">
  <greeting v-bind:persons="persons" v-for="(value,key,index) in persons"></greeting>
</div>

Upvotes: 0

Views: 52

Answers (1)

zero298
zero298

Reputation: 26878

A few things:

  • The template only has access to the props listed, not stuff from the parent scope which is why index is not available
  • You would bind :person="value" since that is the variable that is populated with the current iterated item of persons
  • Add another prop, 'role', so that you can bind the key of the person Object to it

See below:

Vue.component('greeting', {
  template: "<h1>{{person}} is a {{role}}</h1>",
  props: ['person', 'role']
});

var vm = new Vue({
  el: '#app',
  data: {
    persons: {
      'Mike': 'Software Developer',
      'Nikita': 'Administrator Assistant'
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <greeting :person="value" :role="key" v-for="(value, key, index) in persons" :key="index"></greeting>
</div>

Upvotes: 3

Related Questions