Named Route
Named Route: is used to navigate to a component, specifically you may go from component A to B when you click on a link or button.
Example:
product.js file for named route.
Named route is here: name:'product'. product is name of route.
App.vue component file
Below code is how to use named route :
Programmatic navigation.
Inside template navigation:
When you click on any button, you will see below result:
productId:2
Note: impossible to use named route with multiple level routes.
Example:
product.js file for named route.
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 }
path: '/product/:id', name:'product', component: product
App.vue component file
<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/>
<button @click="goProduct(product.id)"> Go to Product</button>
</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'}
]
}
},
methods:{
goProduct( productId = null ) {
if(productId) {
this.$router.push({ name:'product', params:{ id:productId } })
}
}
}
}
</script>
Below code is how to use named route :
Programmatic navigation.
this.$router.push({ name:'product', params:{ id:productId } })
Inside template navigation:
<router-link v-bind:to="{name:'product', params:{ id:product.id }}">Loink</router-link>
When you click on any button, you will see below result:
productId:2
Note: impossible to use named route with multiple level routes.
Comments
Post a Comment