I am trying to use nested routing in my Vue.js application. I have the routing working, however I cannot figure out how to pass data from a parent route down to a child route.
Basically, the parent route is going to retrieve an object that has properties. For each specific nested child route, I want to show one of the properties on that object.
For example, if I have the object below:
myDataObject : {name : "Foo" , profile : "Profile Data", posts : "Posts Data" }
I would like to pass the "profile" variable to the child route "/user/:id/profile". In the case of "/user/:id/posts", I would like to pass the "post" variable in.
I thought I could accomplish this using props, but I cannot find an example that fits with routing and what I tried does not seem to work.
Here is a link to a jsfiddle of what I am trying to do.
http://jsfiddle.net/90q4sucj/2/
This is definitely doable with props
.
In parent component
<template>
...
<router-view :profile="myDataObject.profile" />
...
</template>
In child component
<script>
export default {
name: "child",
props: ["profile"]
...
Now, in your child component you may access the data by referring to this.$props.profile
.
I am using this pattern with Vue 2.5.16. and Vue Router 3.0.1.
PS: A good option is to also use vuex for such scenarios.
See the answer below for the correct answer
! You can retrieve data by using services you create. In the example given I've updated to follow the "fetch data after navigation" sample shown in the docs. It has a
userService
that will handle getting the user's profile.! const userService = { findProfile(id) { return 'Profile Data'; } }; ! Then I updated the UserProfile component to get the profile when it's created and it watches the
$route
for changes.! const UserProfile = { data() { return { profile: null } }, template: 'Profile {{ $route.params.id }} {{ profile }}', methods: { setProfile: function () { this.profile = userService.findProfile(this.$route.params.id); } }, created: function () { this.setProfile(); }, watch: { '$route': 'setProfile' } }
! As for passing it through like
props: []
I didn't see a way but that's probably a good thing because it could start getting pretty convoluted. Here you know explicitly where the user profile is coming from and don't need to follow a rabbit hole to figure it out.! http://jsfiddle.net/90q4sucj/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With