4

I don't understand how to pass data loaded by a 'route Component' to a 'subRoute Component'.. (I'm using Vue.js with Vue-router)

My router looks like that:

router.map({
  '/a': {
    component: A,
    subRoutes: {
      '/b': {
        component: B
      },
      '/c': {
        component: C
      }
    }
  }
});

I just want to share data loaded by component A with component B and C.

Thanks in advance !

1

1 Answer 1

3

You have two simple options.

The ugly

Use the $parent option from the subroute components. That give you access to the parent instance, it's not the recommended way, but it's effective

// from the child component
this.$parent.someData

The good

Use props. Props give you the chance to pass any data from the parent to a child. It's better, because prevents error (you pass data not an instance) and you pass only what you need, even if it isn't part of the parent data.

// parent component
<template>
    <child :childsdata="parentdata"></child>
</template
<script>
    export default {
        data: function () {
            return {
                parentdata: 'Hello!'
            }
        }
    }
</script>

// child component
<template>
    {{ childsdata }} <!-- prints "Hello!" -->
</template>
<script>
    export default {
        props: {
            childsdata: {
                type: String
            }
        }
    }
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

sending data from component B to component C is possible using props?
I found this "<child :childsdata="parentdata"></child>" style answer on many places, but you see under vue-router there is no <child> there is just <router-view> and I would not want to add props to that, as each rout needs a different set of props. This shall be part of the routes object somehow that that vue-router uses.

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.