Nested Route

Nested Route means that routes inside other routes. Route can have multiple levels.

Example:

product.js for route file
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const detail = {
template: `<div> product detail </div>`
}


const product = {
template:`<div>
productId:{{ $route.params.id }}
<router-view></router-view>
</div>`,
watch:{
'$route' (to, from){
console.log(from)
}
},
}
const routes = [
{ path: '/product/:id', name:'product', component: product,
children:[
{ path:'detail', name:'detail', component: detail }
]
}
]

const router = new VueRouter({
routes // short for `routes: routes`
})
export { router }
As you above, i have two components, detail and product

const detail = {
template: `<div> product detail </div>`
}

Product component contains <router-view> which is used to render detail component.
const product = {
template:`<div>
productId:{{ $route.params.id }}
<router-view></router-view>
</div>`,
watch:{
'$route' (to, from){
console.log(from)
}
},
}

Route contains two path, one is product/id and its children contains path, detail
const routes = [
{ path: '/product/:id', name:'product', component: product,
children:[
{ path:'detail', name:'detail', component: detail }
]
}
]
Whenever you have define path as '/product/1/detail', you will see:

                                                productId:2
product detail
this is because <router-view></router-view> insider product component renders detail component as path, product/1/detail renders two components at the same time.

I also have one more file so-called App.vue
<template>
<div id="app">
<h2>Products</h2><br/>
<ul>
<li v-for="product in products" v-bind:key="product.id">
id:{{ product.id }}<br/>
name:{{ product.name }}<br/>
status:{{ product.status }}<br/>
<router-link to="/product/2/detail">show</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</template>

<script>
import { router } from './routes/product';

export default {
name: 'app',
router,
components: {
},
data () {
return {
products:[
{id:1, name:'motobike', status:'old'},
{id:2, name:'fan', status:'new'},
{id:3, name:'watch', status:'new'},
{id:4, name:'glasses', status:'old'}
]
}
},
}
</script>

Final result will be



Comments

Popular posts from this blog

Vuex mapMutations

VueX Actions

VueX Modules