How to Access the Data of the Parent Component in Vue.Js 2

From WikiHTP

The most normal behaviour in Vue.js 2 is to assemble a hierarchy of components to be able to fully segment our application, forms, buttons, content boxes and so on.

Imagine that you have a component called PostsComponent.vue and another called PostComponent.vue, the first one will show all the posts using the second in a loop.

PostsComponent.vue

< template >
  < div >
    < post-component  v-for = " (post, index) in posts " : key = " index " > </ post-component >
  </ div >
</ template >

< script >
import  PostComponent  from  ' ./PostComponent ' ;
export  default {
  name :  ' posts-component ' ,
  components : {
    PostComponent
  },
  data () {
    return {
      posts : [],
      category :  ' Programming '
    }
  },
  mounted () {
    axios . get ( ' https://jsonplaceholder.typicode.com/posts ' )
    . then ( response  =>  response . json ())
    . then ( posts  =>  this . posts  = posts)
  }
}
</ script >

PostComponent.vue

< template >
  < div >
    < div  class = " card "  style = " width: 18rem; " >
        < div  class = " card-body " >
          < h5  class = " card-title " > {{ post . title }} </ h5 >
          < p  class = " card-text " > {{ post . body }} </ p >
          < A  href = " / posts "  class = " btn btn-primary " > Go back </ a >
        </ div >
    </ div >
  </ div >
</ template >

< script >
export  default {
  name :  ' post-component ' ,
  props : {
    post : {
      type :  Object
    }
  }
}
</ script >

How can you see, it's simple, we obtain data to render a series of posts in a list, the important thing here is to look at the category data of the PostsComponent component, the normal thing to use that data in the child component would be the following.

<post-component v-for="(post, index) in posts" :key="index" :category="category"></post-component>

But ofcourse, instead of 1 data to pass, we must pass 10, everything becomes complicated and it becomes quite ugly, to solve this problem, we can use $ parent without modifying the parent component.

< template >
  < div >
    < div  class = " card "  style = " width: 18rem; " >
        < div  class = " card-body " >
          < h5  class = " card-title " > {{ post . title }} - {{ $ parent . category }} </ h5 >
          < p  class = " card-text " > {{ post . body }} </ p >
          < A  href = " / posts "  class = " btn btn-primary " > Go back </ a >
        </ div >
    </ div >
  </ div >
</ template >

< script >
export  default {
  name :  ' post-component ' ,
  props : {
    post : {
      type :  Object
    }
  }
}
</ script >

If you look at the label h5, we are using the category data of the parent component, it is as simple as accessing the data of the parent component in Vue.js 2.

About This Tutorial

This page was last edited on 31 January 2019, at 20:15.