4

This is an easy question but I dont know the best way to do it correctly with Vue2:

Parent Component:

<template>
  <div class="parent">
    <child></child>
    {{value}} //How to get it
  </div>
</template>

Child Component:

<template>
  <div class="child">
    <p>This {{value}} is 123</p>
  </div>
</template>

<script>
export default {
  data: function () {
    return { value: 123 }
  }
}
</script>
2
  • 1
    what if you have multiple children? what's value you expect to get? Commented Dec 12, 2017 at 5:27
  • I fix it clearer @Ben. I want to get VALUE data from CHILD components Commented Dec 12, 2017 at 5:28

2 Answers 2

5

Some ways you can achieve this include:

  • You can access the child VM directly via a ref, but this gets hairy because the ref won't be populated until the child component has mounted, and $refs isn't reactive, meaning you'd have to do something hacky like this:

    <template>
      <div class="parent">
        <child ref="child"></child>
        <template v-if="mounted">{{ $refs.child.value }}</template>
      </div>
    </template>
    
    data() {
      return {
        mounted: false
      }
    },
    
    mounted() {
      this.mounted = true;
    }
    
  • $emit the value from within the child component so that the parent can obtain the value when it is ready or whenever it changes.

  • Use Vuex (or similar principles) to share state across components.
  • Redesign the components so that the data you want is owned by the parent component and is passed down to the child via a prop binding.
  • (Advanced) Use portal-vue plugin when you want to have fragments of a component's template to exist elsewhere in the DOM.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your help! Do you think what is the best way among these your ways?
Ideally you should try to avoid accessing data from a child component (it makes reasoning about the flow of data more difficult in your app), but I suppose #2 is the best way for your scenario.
Thank you I will choose #2. Thanks!
2

Child components pass data back up the hierarchy by emitting events.

For example, in the parent, listen for an event and add the child value to a local one (an array for multiple child elements would be prudent), eg

<child @ready="childVal => { value.push(childVal) }"></child>

and in the child component, $emit the event on creation / mounting, eg

mounted () {
  this.$emit('ready', this.value)
}

Demo ~ https://jsfiddle.net/p2jojsrn/

3 Comments

Thank you for your help!
{{value}} print [123] instead of 123. How can I fix it @Phil
@FeedGit well yeah, I did say it was an array (in case you have multiple child components)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.