Props in component in Vue.js

May 28, 2020

Props in Vue is used to pass data from Parent elements to child element. We will see how it works in this article

Component is useless if you are unable to pass data externally

This component does not have access to the data element in parent Vue instance. You can understand it with following example

 

Vue.component('my-address', {
        template: "
{{street}}
"
    })


    new Vue({
      el: "#root",
      data: {
          active : true,
          street : '23, 2nd Lane',
          city: '',
          state:'',
          zip:'' 
      },
      components:{

      }
    })

You will get the following error

vue:6 ReferenceError: street is not defined
    at a.eval (eval at Tn (vue:6), :2:35)
    at a.t._render (vue:6)
    at a.r (vue:6)
    at Kr.get (vue:6)
    at new Kr (vue:6)
    at vue:6
    at a.Rt.$mount (vue:6)
    at a.Rt.$mount (vue:6)
    at init (vue:6)
    at vue:6

To solve this proplem, we can use props
Here, I am passing the prop street to the component

 

You can add props:['street'] to the Vue instance

Vue.component('my-address', {
        template: "
{{street}}
",
        props:['street']
})