zoukankan      html  css  js  c++  java
  • Vue:router的beforeEach与afterEach钩子函数

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

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

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

    两种函数:

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

    2. Vue.afterEach(function(to,form))/*在跳转之后判断*/

    全局钩子函数

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

    router.beforeEach((to, from, next) => {
        let token = router.app.$storage.fetch("token");
        let needAuth = to.matched.some(item => item.meta.login);
        if(!token && needAuth) return next({path: "/login"});
        next();
    });

    beforeEach函数有三个参数:

    • to:router即将进入的路由对象
    • from:当前导航即将离开的路由
    • next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。

    afterEach函数不用传next()函数

    某个路由的钩子函数

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


    const router = new VueRouter({
      routes: [
        {
          path: '/login',
          component: Login,
          beforeEnter: (to, from, next) => {
            // ...
          },
          beforeLeave: (to, from, next) => {
            // ...
          }
        }
      ]
    })

    路由组件的钩子

    注意:这里说的是路由组件!

    路由组件 属于 组件,但组件 不等同于 路由组件!所谓的路由组件:直接定义在router中component处的组件。如:

    var routes = [
        {
        path:'/home',
        component:home,
        name:"home"
        }
    ]
    

    在子组件中调用路由的钩子函数时无效的。

    在官方文档上是这样定义的:

    可以在路由组件内直接定义以下路由导航钩子
    beforeRouteEnter
    beforeRouteUpdate (2.2 新增)
    beforeRouteLeave

    它是和data,methods平级的。


    beforeRouteLeave(to, from, next) {
        next()
    },
    beforeRouteEnter(to, from, next) {
        next()
    },
    beforeRouteUpdate(to, from, next) {
        next()
    },
    data:{},
    method: {}

     原文地址:https://www.cnblogs.com/WQLong/p/8135553.html

  • 相关阅读:
    android 核心组件( 1 ) 常用布局, adapter, handler, UI
    Android 提高篇 6 之MediaPlayer
    Windows下获取Android系统源码
    Android入门学习笔记之人机用户界面
    Android的三种网络联接方式(URL / HttpURLConnection | HttpClient | InetAddress )
    界面开发的推荐色值, dip,px,pt,sp 的区别
    Android 提高 5 SurfaceView绘图容器的基本使用
    一些腾讯笔试题目
    Android提高篇2 之 Service就是后台程序
    Android提高篇1 之 BroadcastReceiver 应用程序间通信的手段
  • 原文地址:https://www.cnblogs.com/yuzhilai/p/9278251.html
Copyright © 2011-2022 走看看