Search code examples
vue.jsvue-directives

Passing the Properties of an Object in Vue.js


As i learnt from vue.js guide

you can use v-bind without an argument (v-bind instead of v-bind:prop-name).

I treid it, i'm not getting any value.

Vue.component('click-count',{
  data: function(){
    return{
      names: {
        firstName: 'kuldeep',
        lastName: 'Babbar'
      }
    }
  },
  template: `
    <div class="blog-post">
      <p>{{names.firstName}}</p>
    </div>
  `
})
var app = new Vue({
  el: '#root'
});
<div id="root">
  <div >
    <click-count v-bind="names"></click-count>
  </div>
</div>

** New: Forgot to add this image**

enter image description here

can any one explain this?


Solution

  • First, if you try to pass an object "names" from root to child click-count component, the data has to be inside the "root":

    var app = new Vue({
      el: '#root',
      data(){
        return{
          names: {
            firstName: 'kuldeep',
            lastName: 'Babbar'
          }
        }
    })
    

    Now, what you do with v-bind without argument is to pass the object "names" to the component but without a named "names" argument:

    <click-count v-bind="names"></click-count>
    

    is the same as

    <click-count v-bind="{ firstName: 'kuldeep', lastName: 'Babbar' }"></click-count> 
    

    Finally what you pass to your component with v-bind (with or without argument) is props and you need to declare them if you want to use them in your template.
    But in your case, the click-count component doesn't know what names means:

    Vue.component('click-count',{
      props:['firstName', 'lastName'],
      template: `
        <div class="blog-post">
        <p>{{ firstName }}</p>
        </div>
      `
    })
    var app = new Vue({
      el: '#root',
      data(){
        return{
          names: {
            firstName: 'kuldeep',
            lastName: 'Babbar'
          }
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
    <div id="root">
      <div >
        <click-count v-bind="names"></click-count>
      </div>
    </div>


    Edit: To explain the image you linked

    As it says "If you want to pass all the properties of an object as props" means that without argument (<blog-post v-bind="post"></blog-post>), props for the "BlogPost" component are all the properties of post:

    props : ['id', 'title']
    

    used in the component template like that: <p>Title: {{ title }}</p>

    VS when the "post" object is passed as props with an argument (<blog-post v-bind:post="post"></blog-post>), it's under a unique named argument (and not its properties):

    props : ['post']
    

    used in the component template like that: <p>Title: {{ post.title }}</p>