Vue路由
路由
vue-router是在SPA(单页面应用程序)中进行路径之间切换的插件,改变浏览器地址URL,但不重新请求页面,进行视图的更新
1.路由模式(默认是hash模式)
(1).hash模式
(2),history模式
区别:
(1). hash 地址在URL中有#,虽然URL中有hash,但hash不会被包含在HTTP请求中,对后端不会有影响
(2). history模式在URL中没有#,前端的 URL 必须和实际向后端发起请求的 URL 一致,否则返回 404 错误。
2.路由守卫
// 基本使用
router.beforeEach(function(to,from,next){
if(to.path === '/main'){
const token = localStorage.getItem('token');
if(token){
next()
}
else{
next('/login')
}
}else{
next()
}
})
路由参数:
(1). to :表示即将要访问到的页面的路由信息
(2). from :表示即将要离开的页面的路由信息
(3). next() :一个函数,表示放行操作,可先进行判断。如无参数,则访问 to 所对的路由;如有参数,则强制访问参数路由
3. 路由规则
const router = new VueRouter({
routes : [
// 通过 redirect 进行路由的重定向
{path:'/' , redirect : '/Home'},
{path:'/login' , component : Login},
// 嵌套路由:含有子路由的路由规则
{
path : '/about' ,
component : About ,
redirect : '/about/tab1' ,
// 默认子路由:对于 path 为空字符串的路由,称为默认子路由,部分情况类似于重定向
children : [
{path : 'tab1' , component : Tab1},
{path : 'tab2' , component : Tab2}
]},
// 开启 props 传参,可以不用通过 prams 获取 id
{path : '/movie/:id' , component : Movie , props : true},
{},
...
]
})
基本参数:
(1). path :路由的URL地址
(2). component :组件名,即该路由使用的组件
(3) .name : 命名路由-路由名称
(4). redirect : 路由重定向
4. 路由对象route
和router
的区别
route 是“路由信息(参数)对象”,包括 path,params,hash,query,fullPath,matched,name 等路由信息参数。
router 是“路由实例(导航)对象”,包括了路由的跳转方法(push、go),钩子函数等。
5.路由跳转的基本方式
(1). <router-link to='/home/users'>
相当于 HTML 中的 a链接
(2). this.$router.push('/home/users')
相当于 push 一个页面,回退会返回上一个页面
(3). this.$router.replace(/home/users)
相当于对当前页面进行 replace 操作,回退会返回上上个页面
os : 假设从 /detail 访问 /login ,再通过 /login 中的this.$router.push('/home/users')
语句进行访问 /home/users,回退则会回到 /login
os : 假设从 /detail 访问 /login ,再通过 /login 中的this.$router.replace('/home/users')
语句进行访问 /home/users,回退则会回到 /detail
(4).this.$router.go(n)
向前或向后跳转 n 个页面,n 可为正数或负数
(5).this.$router.back()
回退到上一个页面
6. 路由参数的传递
(1). query查询
<!-- 在 hash 地址中,? 后面的参数项,叫做查询参数 -->
<!-- 查询参数需要用 this.$route.query 来访问 -->
<!-- this.$route中 path 是路径部分,fullpath 是完整地址 -->
<!-- /movie/2?name=zs 是fullpath -->
<!-- /movie/2 是path -->
(2). parms
通过this.$route.parms.id
传递动态参数
比如在写一个商品详情页面的时候,我们的页面结构都一样,只是渲染的数据不同而已,这时候就可以根据商品的不同id去设置动态路由,只需要写一个组件,就可以把每个商品的商品详情映射到同一个组件上去。
{
path: '/Jqxq/:id', // 路由配置拼接
name: 'Jqxq',
component: Jqxq
}
跳转 this.$router.push('/Jqxq/'+ item.id)
接收 : this.$route.params.id
(3). 在该组件路由规则中允许 props 传参props:true
,可替代 parms 传参
7.路由懒加载
使用原因:在单页应用中,如果没有应用懒加载,运用 webpack 打包后的文件将会异常的大,造成进入首页时,需要加载的内容过多,延时过长,不利于用户体验,而运用懒加载则可以将页面进行划分,需要的时候加载页面,可以有效的分担首页所承担的加载压力,减少首页加载用时 原理:vue 异步组件技术:异步加载,vue-router 配置路由 , 使用 vue 的异步组件技术 , 实现按需加载。
{ path: '/home', component: () => import('@/views/home/home.vue') }
// 懒加载