Programmatic Navigation
Programmatic Navigation: means we are possibly to navigate to a component by using $router instance rather than <router-link :to="#"></router-link>.
Example:
product.js route file
App.vue component file which contains goProduct method.
When you click on Go to Product button, you see :
productId:2
product detail
that means it renders product and detail component as it was nested route.
Programmatic navigation is here
Navigation can be done with different syntax, more detail here: https://router.vuejs.org/guide/essentials/navigation.html
final result
Example:
product.js 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 }
App.vue component file which contains goProduct method.
<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({ path: `/product/${productId}/detail` })
}
}
}
}
</script>
When you click on Go to Product button, you see :
productId:2
product detail
that means it renders product and detail component as it was nested route.
Programmatic navigation is here
this.$router.push({ path: `/product/${productId}/detail` })
You may see the each time you click on button the $router instance pushes path to get components rendered.Navigation can be done with different syntax, more detail here: https://router.vuejs.org/guide/essentials/navigation.html
final result

Comments
Post a Comment