【关于vue的路由(导航)的知识的学习】
目录
1、什么是路由?
路由是指路径和组件的一 一 对应关系
2、路由模式
vue有两种路由模式 :hash 和 history ;默认是 hash 模式
区别:hash 模式会带#号,不美观
history 不带#号,(使用时会向后台请求接口,易报404错误)
3、路由(导航)的跳转
声明式导航:router-link to=" 要跳转的页面路径"
编程式导航:this.$router.push()
4、vue 的路由传参数
(1)、query 传参:
既可以使用 name 也可以使用 path ,刷新页面参数不会丢失
this.$router.push({
name:'',
path: '',
query: {}
})
this.$router.push('/info?canshu1=1&canshu2=2')
//如何接受query参数:
// this.$route.query.属性名
(2)、params 传参:
只能使用 name 跳转,刷新的时候参数会丢失,不会显示到页面的 url 上
this.$router.push({
name:'',
params: {}
})
//如何接受params参数:
// this.$route.params.属性名
(3)、动态路由传参:
刷新的时候数据不会丢失
{
path: '/info/:name/:age',
name: 'info',
component:()=>import('../views//info.vue')
}
//接收参数
this.$route.params
5、嵌套路由(子路由)
嵌套路由常用于侧边导航,底部路由导航。
使用:
(1)、在展示的页面设置 <router-view/> 为第二个坑
(2)、在第二个坑的页面路由下设置子路由,使用 children
{
path: '/',
name: 'Home',
component: Home,
children: [
{
path: '/about',
name: 'About',
component: function () {
return import( '../views/About.vue')
}
},
{
path: '/my',
name: 'my',
component: ()=>import('../views/my.vue')
},
]
},
6、路由导航守卫
路由导航守卫分三种:
(1)、全局导航守卫(在 router 文件夹下的 index.js 文件,在文件导出之前)
全局前置导航守卫:beforeEach
语法:
router.beforeEach((to,from,next)=>{
// to -- 到哪里去
// from -- 从哪里来
// next -- 下一步 重定向
})
全局后置导航守卫:afterEach
语法:
router.afterEach((to,from)=>{
})
全局解析守卫:beforeResolve
(2)、组件导航守卫(有3个,在要拦截的页面写)
// 路由进入之前
beforeRouteEnter(to,from,next){
}
// 路由更新
beforeRouteUpdate(to,from,next){
}
// 路由离开之前
beforeRouteLeave(to,from,next){
}
(3)、单个独享的路由守卫(在路由下面写):beforeEnter