下载router
yarn add vue-routrer
引入router
// 引入路由
import Router from "vue-router";
注册router
// 注册全局
Vue.use(Router)
使用router
完整代码
import Vue from 'vue'
// 引入路由
import Router from 'vue-router';
// 注册全局
Vue.use(Router)
// 设置路由
const routes =[
{
path:'*', //默认路径
redirect:'/a' //默认的路由路径
},
{
path:'/a', //路由路径
component:()=>import('vue文件路径')
},
{
path:'/b', //路由路径
component:()=>import('vue文件路径'),
children:[ // 设置二级路由
{
path:'bb', //路径不要/
component:()=>import('vue文件路径'),
}
]
}
]
const rotuer = new Router({
routes,
mode:'history' //默认是哈希模式 hash 带#
})
export default rotuer
router和route的区别
this.$router:使用的方法,操作对象
this.$route:当前路由信息
router-view和router-link的区别
router-view:
router-link:相等于a标签,需要用to属性作为路由路径
路由跳转方式
push方式:
this.$router.push('/a')
// 或
this.$router.push({path:'/a'})
// 或
this.$.router.push({name:'路由名字'})
router-link方式:
<router-link to:'/a'>点击跳转</router-link>>
- 使用path方式跳转路由 path会忽略params 所以path不能和params一起使用
- 推荐使用name和query方式实现路由跳转
params传参,push里面只能是 name:‘xxx’,不能是path:‘/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!
路由传值
方式1
<router-link to:'/a?name=小明'></router-link>
<!-- 对应页面接收 -->
<!-- $route.params.参数名 -->
$.route.params.name
方式2
<!-- to:'/path/' (需在路由规则里配置/path/:参数名) -->
<!-- 例:to="/part/小王" -->
<!-- 配置:path:"/part/:name" -->
<router-link to:'/a/小明'></router-link>
<!-- 对应页面组件接收传递过来的值 (注意动态参数需要用params接收) -->
<!-- 对应页面接收 -->
<!-- $route.params.参数名 -->
$route.params.name
路由参数
query相当于GET请求,页面跳转的时候,可以在地址栏看到请求参数
params相当于POST请求,参数不会在地址栏中显示
// 通过params传参
this.$router.push({
name:"Home",
params:{
id:this.id
}
})
// 另一个页面接收
this.$route.params.id
// 通过query传参
this.$router.push({
path:"/Search",
query:{ //query是个配置项
age:20
}
})
// 另一个页面接收
this.$route.query.age
路由守卫
对路由进行权限控制
当满足条件时,才进行路由切换
如何给路由添加一个权限判断呢?
例如,用户在登录的状态下就能去到某页面,但是未登录则给你弹出一个未登录的提示。
路由守卫的目标是实现这样一个权限判断,在路由跳转之前,会触发一个函数.
全局守卫
全局的路由守卫所有组件都会经过。
beforeEach 前置守卫
// to 表示要去哪里
// from 表示从哪里来
// next 表示是否方向
// next(false) 表示不能通过
// next('/login')表示跳转到登录页面
// next() //正常放行
// 不写next()默认是通不过的,此时也不能进入页面。
router.beforeEath((to,form,next) => {
})
affterEach 后置守卫
全局后置守卫:初始化时执行、每次路由切换后执行,没有next参数
beforeResolve 解析守卫
组件路由守卫
beforeRouterEnter 进入组件之前触发,在Created前面
beforeRouterUpdated 路由更新但是内容不会改变
beforeRouterLeave 离开之前触发,在beforeDestory之前触发
路由独享守卫
beforeEnter 读取路由的信息
作用:主要是读取当前路由的信息。某一个路由独有的路由守卫
独享路由守卫只有 beforeEnter
beforeEnter 和 全局后置守卫 可以同时使用,不冲突!
const roues = [
{
path:'/a', //路由路径
component:()=>import('vue文件路径'),
beforeEnter:(to,form,next) =>{...} //独享路由守卫
}
]