Dynamic Route

Dynamic Route is very important to know this route due to with real world app, you will frequently use it. this means that route with parameters.
In case routes or named routes are duplicated, the order of route will be used as the first will be prioritized.

Example:

route file

product.js
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

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

const router = new VueRouter({
routes // short for `routes: routes`
})
export { router }

Here is dynamic route: meaning that id can be any number, 1, 2,3...
{ path: '/product/:id', name:'product', component: product }

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 v-bind:to="{name:'product', params:{ id:product.id } }">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>

Below is how we use dynamic route in template :
<router-link v-bind:to="{name:'product', params:{ id:product.id } }">show</router-link>

Final result :


In order to see your dynamic route performs, you can following below:
watch:{
'$route' (to, from){
console.log(from)
}
},
When you click on any show button, you may see to or from in console log.

Note: route instance can be access by $route or router.

productId:{{ $route.params.id }}



Comments

Popular posts from this blog

Vuex mapMutations

VueX Actions

VueX Modules