0
votes

Currently I have these routes:

{ path: '/:username', component: Profile, children: [
    { path: '', component: Map , name: 'Profile'},
    { path: 'locations', component: Locations, name: 'Locations'},
    { path: 'map', component: Map, name: 'Map'}
]},

I need a markers: [] array which gets populated on from my database on mounted() execution. This array will be used in both Map and Locations components.

What is the best way of doing this. I can:

  • Have property markers: [] and mounted() lifecycle hook in the local state of each component and just execute an axios call on each component. This means 2 axios calls.
  • Have property markers: [] and mounted() lifecycle hook in the local state of the parent of those 2 components and then Props down the data to each component. This means 1 axios call and then I just pass down the data

However, in the second case, I don't know if I would I be able to pass down data in Props since I'm not sure if the components in the nested routes are actually children of the parent element.

1

1 Answers

1
votes

Short answer is yes if your Profile contains a router-view you can acces markers using $parent or pass it using props:

const Profile = Vue.extend({
  template: `<div>
        Profile {{ markers}}
        <!-- pass as props (used by Loaction) -->
        <router-view :markers="markers"></router-view>
    </div>`,
  data() {
    return {
      markers: []
    }
  },
  mounted() {
    // fake load
    setTimeout(() => {
      this.markers = ['A', 'B', 'C'];
    }, 1000);
  }
})
const Map = Vue.extend({
  template: `<div>
    <!-- uses $parent to get markers -->
    Map {{ $parent.markers}} 
  </div>`,
})
const Locations = Vue.extend({
  props: ['markers'],
  template: `<div>
    <!-- uses props to get markers --> 
    Locations {{ markers}} 
  </div>`,
})



const routes = [{
    path: '/',
    redirect: 'Profile'
  },
  {
    path: '/:username',
    component: Profile,
    children: [{
        path: '',
        component: Map,
        name: 'Profile'
      },
      {
        path: 'locations',
        component: Locations,
        name: 'Locations'
      },
      {
        path: 'map',
        component: Map,
        name: 'Map'
      }
    ]
  }
]
const router = new VueRouter({
  routes
});

new Vue({
  router,
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.js"></script>




<div id="app">
  <router-view></router-view>
  <router-link :to="{name:'Profile'}">Profile</router-link>
  <router-link :to="{name:'Map'}">Map</router-link>
  <router-link :to="{name:'Locations'}">Locations</router-link>
</div>