在路由跳转的时候,我们需要一些权限判断或者其他操作。这个时候就需要使用路由的钩子函数。

定义:路由钩子主要是给使用者在路由发生变化时进行一些特殊的处理而定义的函数。

总体来讲vue里面提供了三大类钩子,两种函数 1、全局钩子 2、某个路由的钩子 3、组件内钩子

两种函数:

. router.beforeEach(function(to,form,next){}) /*在跳转之前执行*/

. router.afterEach(function(to,form)}{}) /*在跳转之后判断*/
全局钩子函数

顾名思义,它是对全局有效的一个函数

// router.js

const router = new Router({
routes: [
{
path: '/',
name: 'sideBar',
component: sideBar,
children:[
{
path:'/',
name:'sort',
component:sort
},
{
path:'/addNewSort',
name:'addNewSort',
component:addNewSort
},
{
path:'/notSend',
name:'notSend',
component:notSend
},
{
path:'/sended',
name:'sended',
component:sended
},
}
]
}) router.beforeEach((to,from,next)=>{
// console.log("to:",to); // router即将进入的路由对象
// console.log("from:",from); // 当前导航即将离开的路由
// console.log("next:",next); // Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
if(to.name=='notSend'){
next({
name:'sort'
})
return
}
next()
}) export default router
某个路由的钩子函数

顾名思义,它是写在某个路由里头的函数,本质上跟组件内函数没有区别。

// router.js

const router = new VueRouter({
  routes: [
{
path: '/login',
component: Login,
beforeEnter: (to, from, next) => {
// ...
},
beforeLeave: (to, from, next) => {
// ...
}
}
]
})
路由组件的钩子

可以在路由组件内直接定义以下路由导航钩子

// *.vue

beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave

这里简单说下钩子函数的用法:它是和data,methods平级的。

beforeRouteLeave(to, from, next) {
next()
},
beforeRouteEnter(to, from, next) {
next()
},
beforeRouteUpdate(to, from, next) { // 用于相同路由组件的的参数更新
next()
},
data:{},
method: {}

最新文章

  1. AngularJs之四
  2. 适配各种Windows分辨率,为DPI添加感知,当在高DPI时,禁用WINFORM缩放等。
  3. POJ 2155 2维线段树 || 2维BIT
  4. SVM3 Soft Margin SVM
  5. Javascript - 数组去重复
  6. extjs 学习笔记(二)
  7. InnoDB外键使用小结
  8. Java多线程——Executors和线程池
  9. css中的段落样式及背景
  10. 浅谈 Mybatis中的 ${ } 和 #{ }的区别
  11. Python300篇电子书免费送
  12. 将web项目导入到eclipse中常见错误
  13. php-- orther
  14. Javascript概念
  15. C#比较两个字符串的相似度【转】
  16. C#委托举例
  17. Java,vue.js,jsp for循环的写法
  18. JavaScript 对象属性
  19. Django的视图响应类型
  20. Django【进阶】modelform

热门文章

  1. iphone通讯录的备份与恢复
  2. vc++实例创建简单窗体
  3. Python笔记23------Python统计列表中的重复项出现的次数的方法
  4. MAC上ITERM2配置SZ, RZ远程上传和下载文件
  5. ApacheBench 测试性能并使用 GnuPlot 绘制图表
  6. PHP 一句话木马
  7. Project Euler 28 Number spiral diagonals
  8. hdu 4826
  9. Centos6下创建Centos6基础镜像
  10. centos 如何执行.bin 文件??