I'm trying to figure out how child routes in VueJS work. I would think that if I had a news overview with links to each news item, I could then use a child route to view the news item, but it doesn't works as I expects.
Is it me that is doing it wrong or?
const router = new VueRouter({
routes: [
{
path: '/news',
name: 'news',
component: News,
children: [
{
path: ':id',
name: 'newsitem',
component: Newsitem
}
]
}
]
});
I have created a jsfiddle to show how I would expect it to work.
If I uncomment the router in the javascript, then it works fine, but not with children.
This allows you to leverage the component nesting without having to use a nested URL. As you can see the children option is just another Array of routes like routes itself. Therefore, you can keep nesting views as much as you need.
To recap, nested routes allow you to, at the route level, have a parent component control the rendering of a child component. Twitter's /messages route is the perfect example of this. With React Router, you have two options for creating nested routes.
Vue router: Vue Router helps link between the browser's URL/History and Vue's components allowing for certain paths to render whatever view is associated with it. A vue router is used in building single-page applications (SPA). The vue-router can be set up by default while creating your new project.
Like Moersing.Lin said you forgot to put a <router-view>
in your News Component.
Here is an working example of your fiddle:
const News = {
template: `<div>
<h1>News</h1>
<br><br>
<router-view></router-view>
</div>
`
}
const Newsitem = {
template: "<h2>News {{this.$route.params.id}}</h2>"
}
const router = new VueRouter({
routes: [{
path: '/news',
name: 'news',
component: News,
children: [{
path: ':id',
name: 'newsitem',
component: Newsitem,
}]
}]
});
new Vue({
el: '#app',
router,
}).mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<ul>
<li>
<router-link :to="{ name: 'news'}">News list</router-link>
</li>
<li>
<router-link :to="{ name: 'newsitem', params: { id: 'item-1' }}">Item 1</router-link>
</li>
<li>
<router-link :to="{ name: 'newsitem', params: { id: 'item-2' }}">Item 2</router-link>
</li>
</ul>
<router-view></router-view>
</div>
I got it, A Vue Router is required <router-view></router-view>
,but in your code, The root
component is there, but you forgot the parent
,it needs a <router-view></router-view>
too.
https://jsfiddle.net/v28yw3g5/
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