不怎么常用方法:
- this.$router.go(-1)后退一步记录,相当于history.ba()
- this.$router.go(1)前进一步,相当于history.forward()
路由参数传递:
1.通过<router-link>标签的to传参
<router-link :to = “{name:xxx,params:{key:value}}”></router-link>
name:对应的是路由配置文件中使用的name值,即路由名称
params:以对象形式出现,可以传多个值
2.在URL中传递参数
路由配置文件:
{
path:’two/:id/:name’
component:Two
}
在Two.vue中:
<p>ID:{{$route.params.id}}
<p>名称:{{$route.params.name}}
跳转:
<router-link to:”/home/two/666/花仙子”>页面2</router-link>
3.编程式导航
methods:{
toThreePage(){
this.$router.push({name:’three’,params:{id:1,name:’beixi’}})
}
}
!注意:
- 使用params传递参数,this.$router.push()方法中path和params不能同时使用,不然params会失效,可以用name指定页面。
- 如果路由配置文件中这么写path:’three/:id/:name’传递的参数不会显示到浏览器的地址栏中,而且刷新一次页面就获取不到参数了。可以改成path:’/home/three/:id/:name’
路由中router和route的区别:
1.router
- $router.push({path:’home’});切换路由,有history记录
- $router.replace({path:’home’});替换路由,没有历史记录
2.route
- $route.path
- $route.params
- $route.name
- $route.query
路由监听
watch:{
$route:{
handler(to,from){
const xx=to.query.id
this.xx=xx
},
deep:true
}
}
动态路由(以三种身份登录跳转不同页面为例):
- 路由表export contantRouterMap和asyncRouterMap,实例化的时候只挂载contantRouterMap。设置meta:{role:[‘admin’,’super-editor’]}(!404页面要最后加载)。
- 登录按钮执行vuex中的方法,把token存在session storage中(?)根据身份跳转this.$router.push(“/”+res.data.type)
- 路由拦截beforeEach(1.判断是否跳到login页面放行2.else判断是否有身份信息没有获取并next(...to,replace:true)否则放行)
- menu.js文件两个参数:routers:router.options.routes两个方法:getMenus、hasPermission
- default-active=”$route.path”
!注意:this.$route只能在组件中使用,如果在js中使用,需引入(import store from ‘@/store’)(例:store.state.menu.addRouters)
参考:
1.贾志杰《前后端分离开发实战》