前端路由

根据不同的事件来显示不同的页面内容,即事件与事件处理函数之间的对应关系

前端路由是基于hash值的变化进行实现的

简单使用

<div id="app">
    <router-link to="/user">user</router-link>
    <router-link to="/register">register</router-link>
    <!-- 组件显示占位符 -->
    <router-view></router-view>
</div>
// 两个组件
let user = {
    template: '<div>user</div>'
};
let register = {
    template: '<div>register</div>'
};
// 定义路由组件映射规则
let router = new VueRouter({
    routes: [
        { path: '/user', component: user },
        { path: '/register', component: register }
    ]
})
let vm = new Vue({
    el: '#app',
    // 将路由挂载到vue实例
    router
})

路由重定向

{ path:"/",redirect:"/user"}

嵌套路由

let User = {
    template: `<div>
    user
        <router-link to="/user/add">user add</router-link>
        <router-link to="/user/delete">user delete</router-link>
        <router-view></router-view>
    </div>`
};
let UserAdd = {
    template: `<div>this is user add page</div>`
};
let UserDelete = {
    template: `<div>this is user delete page</div>`
};
{
    path: '/user',
    component: User,
    children: [
        { path: '/user/add', component: UserAdd },
        { path: '/user/delete', component: UserDelete },
    ]
}

动态路由

<router-link to="/register/1">register1</router-link>
<router-link to="/register/2">register2</router-link>
{ path: '/register/:id', component: register }
<div>register id:{{$route.params.id}}</div>
let register = {
    props:['id'],
    template: '<div>register id:{{id}}</div>'
};
// 如果props设置为true,route.params将会被设置为组件属性
{ path: '/register/:id', component: register,props:true }
// 可以将props设置为对象,那么就直接将对象的数据传递给组件进行使用
{ path: '/register/:id', component: register,props:{name:'cxk',age:18} }
// props设置为函数形式,该函数能访问router.params
{ path: "/user/:id", component: User,props:(route)=>{
    return {username:"jack",pwd:123,id:route.params.id}
} 

命名路由

<router-link :to="{name:'user'}">user</router-link>
{
    name:'user',
    path: '/user',
    ...
}

编程式导航

this.$router.push('/register/1');
this.$router.go(-1); // 后退