[Vuejs]-Accessing called component data in main template

2👍

You cannot access the scope of a child component within the parent. Usually, you would load the required data in the parent, if you are needing it there, and then pass it along to the child component as a prop like this:

ParentComponent:

<template>
  <sub-item-component sub-item="subItem"></sub-item-component>
  <p v-for="subItem in subItems>{{ subItem.title }}</p>
</template>

<script>
import SubItemComponent from '...';

export default {
  name: 'ParentComponent',
  components: {
    SubItemComponent
  },
  data () {
    return {
      subItems: []
    };
  }
}
</script>

SubItemComponent:

<template>
  {{ subItem }}
</template>

<script>
export default {
  name: 'SubItemComponent',
  props: {
    subItem: {
      type: Array,
      required: true
    }
  }
}
</script>

You could also use a Vuex store to persist the data in one place. With this approach you would have access to the data from each component and do not have pass the data from component to component. To use a store like Vuex, you need to define a Vuex state and at least one mutation method to add the data.


If you want to communicate from the child up to the parent, the way to go would be by using events. You would use a listener on the child component in the parent component like this:

<sub-item-component @new-sub-item="handleNewSubItem"></sub-item-component>

You need to define a method handleNewSubItem in the parent, which is reacting each time the new-sub-item event is thrown in the child component.

The event can then be thrown within the script part of the child component like this:

const subItem = { test: 123 };
this.$emit('new-sub-item', subItem);

1👍

You don’t. Your options are:

  • The parent component needs to manage the data and pass it down to its children via props. Child components can then subsequently emit events which the parent can listen for and modify its state.
  • Use a state handler outside of both the components like Vuex or Apollo (if using GraphQL).

Leave a comment