基础
- router是路由器
- routes是一组路由
- route某个路由(route.query、route.params、route.hash--#后面的,包含#)
const router = new VueRouter({
routes
})
new Vue({
router,
})
- hash模式
以参数形式传给单页面文件,只需要保证index.html这个文件路径真实就可以了
- history模式
这种模式需要后端支持,因为如http://xxx/自定义路径在单页面应用中是没有的
服务器需要增加所有情况的候选资源,让它们都返回同一个index.html文件
<router-view>
<router-link :to="{path: 'apple', query: {color: 'red' }}">
<router-link :to="{name: 'applename', params: { color: 'red' }}">
单个路由配置、动态路由匹配、动态添加路由配置
{
path: '/user/:id',//path是地址栏#后面的东西
props:true,//可以将路由的参数作为属性传递到组件中
name: 'user',//有name时,当前路由变成唯一的了
component: User,
component: () => import('../views/User.vue'),//延迟加载(用到的时候加载)
redirect: '/home',//重定向
children:[
{
path: 'collection',// 主路由上的path会被自动添加到子路由之前
name: 'collection',
component: Collection
},
]
}
- 使用场景
同一个组件,路径参数一样,展示有所不同
- 匹配模式、匹配路径、参数获取
匹配模式:/users/:username /users/:username/:userid
匹配路径:/users/jim /users/jim/123
参数获取:route.params.username route.params.userid
let routesA = [
{path:'/aList',component:AList},
{path:'/aDetail',component:ADetail},
]
if(role == 'A'){
router.addRoutes(routesA)
}
导航
<router-ling to="">
push 、replace 、 go(n)
router.push({path: '/detail', query:{}})
router.push({name: 'detail', params:{}}) // 这里的name对应路由配置中的name,大小写敏感
// 使用参数
route.query.xx
route.params.xx
路由守卫
1、to 将要进入的路由
2、from 当前导航正要离开的路由
3、next 表示放行,必须严格保证该方法起码被调用一次,易出现死循环的现象
next() next({name: 'detail'}) next({path: '/detail'})
- beforeEach
- afterEach
{
path:'/home',
component: Home,
beforeEnter:(to,from,next)=>{...}
}
beforeRouteEnter:进入组件时
beforeRouteUpdate:路由不变,传递的参数改变
beforeRouteLeave: 离开组件前