Redirect and Alias

Redirect and Alias : redirect means when you user visits '/a' , url will be replaced by '/b' while Alias means user see '/b' url whereas the real url is '/a'. 

Example:
path:'products',
name:'products',
redirect: 'detail'
 As you see above if there is no redirect: 'detail', when you click on product all button, you see list of product with product status but with redirect keyword you may see product detail.

full example: product.js
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const navBar = {
template: `<div>
<ul>
<li><router-link v-bind:to="{ path:'products' }">Product all</router-link></li>
<li><router-link v-bind:to="{ path:'detail' }">Product detail</router-link></li>
</ul>
</div>`
}

const setting = {
template: `
<div>
<navBar />
<router-view />
<router-view name='status' />
<router-view name='detail' />
</div>`,
components:{
navBar
}
}

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

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

const products = {
template:`<div>
<li v-for="product in products" v-bind:key="product.id">
id: {{product.id}}, name: {{product.name}}, status: {{ product.status}}
</li>
</div>`,
watch:{
'$route' (to, from){
console.log(from)
}
},
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'}
]
}
},
}
const routes = [
{ path: '/',
name: 'setting',
component: setting,
children:[
{
path:'products',
name:'products',
redirect: 'detail',
components:{
default:products,
status:status
}
},
{
path:'detail',
components:{
detail:detail
}
}
]
}
]

const router = new VueRouter({
mode:'history',
routes // short for `routes: routes`
})
export { router }
Redirect can also be done with named route:
redirect: { name: 'detail' },

Alias example
path:'products',
name:'products',
alias: 'list',
components:{
default:products,
status:status
}

In template:
<li><router-link v-bind:to="{ path:'list' }">Product all</router-link></li>
The actual name of route is products however, we alias as list. when user clicks on Product all button, url is /list and user see list of product.

App.vue component.
<template>
<div id="app">
<h2>Products</h2><br/>
<router-view></router-view>
</div>
</template>

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

export default {
name: 'app',
router,
methods:{
goProduct( productId = null ) {
if(productId) {
this.$router.push({ name:'product', params:{ id:productId } })
}
}
}
}
</script>

Comments

Popular posts from this blog

Vuex mapMutations

VueX Actions

VueX Modules