目前,我有以下路线:
{ path: '/:username', component: Profile, children: [
{ path: '', component: Map , name: 'Profile'},
{ path: 'locations', component: Locations, name: 'Locations'},
{ path: 'map', component: Map, name: 'Map'}
]},
我需要一个markers: []
数组,该数组在执行mounted()
时从我的数据库中填充。此数组将在Map
和Locations
组件中使用。
执行此操作的最佳方法是什么。我可以:
markers: []
和mounted()
生命周期挂钩
每个组件的本地状态,只需在每个组件上执行axios调用
零件。这意味着有2次axios呼叫。markers: []
和mounted()
生命周期挂钩
这两个组成部分的父级的本地状态,然后向下按
数据到每个组件。这意味着有1次axios调用,然后我只是将数据传递给了但是,在第二种情况下,我不确定是否可以在Props中传递数据,因为我不确定嵌套路由中的组件是否实际上是父元素的子元素。
答案 0 :(得分:1)
如果您的个人资料包含路由器视图,则简短答案是肯定的,您可以使用$ parent来访问标记,也可以使用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>