Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you pass data from a parent route to a child route in Vue.js nested routes?

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/

like image 740
Dave Avatar asked Jan 06 '17 16:01

Dave


2 Answers

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.

like image 157
jedik Avatar answered Nov 16 '22 23:11

jedik


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/

like image 21
Stephen Gilboy Avatar answered Nov 16 '22 23:11

Stephen Gilboy