Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。路由实际上就是可以理解为指向,就是我在页面上点击一个按钮需要跳转到对应的页面,这就是路由跳转
路由跳转
- 以新的窗口模式跳转
getRegister() {
const {href} = this.$router.resolve({
path: `/register`
});
window.open(href, '_blank');
},
- 声明式跳转
<router-link :to="...">
- 编程式跳转
// 字符串
router.push('home')
// 对象
this.$router.push({path: '/login?url=' + this.$route.path});
// 带查询参数,变成/backend/order?selected=2
this.$router.push({path: '/backend/order', query: {selected: "2"}});
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
- 不会返回的跳转 router.replace(location)
设置 replace 属性(默认值: false)的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。即使点击返回按钮也不会回到这个页面。加上replace: true后,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
//声明式:
<router-link :to="..." replace></router-link>
// 编程式:
router.replace(...)
//push方法也可以传replace
this.$router.push({path: '/home', replace: true})
路由传参
-
使用query
地址栏会暴漏传的参数
//存进去
this.$router.push({
path: '/home',
query: {
site: [],
bu: []
}
})
//取出来
this.$route.query.site
-
使用params
地址栏不会暴漏传的参数
//存进去
this.$router.push({
name: `xxx`,
params: {
page: '1', code: '8989'
}
})
//取出来
this.$route.params.page
-
路由拼接的方式
在路由中写
{
path:'/one/reg/:num',
component:Reg,
}
//取出来
this.$route.params.num
- 全局路由守卫
router.beforeEach((to, from, next) => {
console.log(to) => // 到哪个页面去?
console.log(from) => // 从哪个页面来?
next() => // 一个回调函数
}
router.afterEach(to,from) = {}
- 组件路由守卫
跟methods: {}等同级别书写,组件路由守卫是写在每个单独的vue文件里面的路由守卫
beforeRouteEnter (to, from, next) {
// 注意,在路由进入之前,组件实例还未渲染,所以无法获取this实例,只能通过vm来访问组件实例
next(vm => {})
}
beforeRouteUpdate (to, from, next) {
// 同一页面,刷新不同数据时调用,
}
beforeRouteLeave (to, from, next) {
// 离开当前路由页面时调用
}
-
路由独享守卫
路由独享守卫是在路由配置页面单独给路由配置的一个守卫
export default new VueRouter({
routes: [
{ path: '/',
name: 'home',
component: 'Home',
beforeEnter: (to, from, next) => {// ...
}
}
]
})
网友评论