zoukankan      html  css  js  c++  java
  • vue-router 的钩子

    1)全局钩子函数
            定义在全局的路由对象中,主要如下:
            beforeEach  在路由切换开始时调用
            afterEach     在每次路由切换成功进入激活阶段时调用
    2)单独路由独享的钩子
          可以在路由配置上直接定义beforeEnter钩子
    3)组件的钩子函数:
               定义在组件的router选项中
               beforeRouteEnter   
               beforeRouteUpdate
               beforeRouteLeave
     
    前置钩子
    // to :是要去的那个页面 路由相关的参数 (表示 将要访问的那个路由对象)
    // from :从哪个页面即将离开 (从哪个路由对象,跳转而来)
    // next :next 是一个函数,就相当于 Node 里面 express 中的 next 函数 (代表放行)
           // next() 表示放行 next('/login') 表示强制跳转到login页
    // 注意: 这里的 router 就是 new VueRouter 得到的 路由对象
    router.beforeEach((to, from, next) => {
        if (to.matched.some(item => item.meta.may)) {
            let id = window.localStorage.getItem("id")
            if (id) {
                next()
            } else {
                next({ name: "login" })
            }
        } else {
            next()
        }
    })
    这三个参数 to 、from 、next 分别的作用:
    to: Route,代表要进入的目标,它是一个路由对象
    from: Route,代表当前正要离开的路由,同样也是一个路由对象
    next: Function,这是一个必须需要调用的方法,而具体的执行效果则依赖 next 方法调用的参数
      next():进入管道中的下一个钩子,如果全部的钩子执行完了,则导航的状态就是 confirmed(确认的)
      next(false):这代表中断掉当前的导航,即 to 代表的路由对象不会进入,被中断,此时该表 URL 地址会被重置到 from 路由对应的地址
      next(‘/’) 和 next({path: ‘/’}):在中断掉当前导航的同时,跳转到一个不同的地址
      next(error):如果传入参数是一个 Error 实例,那么导航被终止的同时会将错误传递给 router.onError() 注册过的回调
     
    注意:next 方法必须要调用,否则钩子函数无法 resolved
     
    后置钩子
    router.afterEach((to,from) => {
        if(to.meta && to.meta.title){
            document.title = to.meta.title
        }else{
            document.title = "666"
        }
    })
     
    单独路由钩子
    //
    //
    {
        path: '/home',
        name: 'home',
        component: Home,
        beforeEnter(to, from, next) {
            if (window.localStorage.getItem("id")) {
                next()
            } else {
                next({ name: "login" })
            }
        }
    }
     
    组件内的钩子
     
    beforeRouteEnter(to, from, next) {
        // do someting
        // 在渲染该组件的对应路由被 confirm 前调用
    },
    beforeRouteUpdate(to, from, next) {
        // do someting
        // 在当前路由改变,但是依然渲染该组件是调用
    },
    beforeRouteLeave(to, from ,next) {
        // do someting
        // 导航离开该组件的对应路由时被调用
    }
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    vue-router钩子
  • 相关阅读:
    终端不显示 git branch 名字
    多线程下bufferedwriter若不关闭并不能记下所有log
    anaconda prompt execute jupyter notebook, can't open notebook
    conda 创建新环境下载包失败
    failed to install jupyter_contrib_nbextensions
    failed to install nb_conda
    Windows Server 2012R2 修复CVE-2016-2183(SSL/TLS)漏洞的办法
    SSL/TLS协议信息泄露漏洞(CVE-2016-2183)解决办法
    记录win NFS公网映射开放端口
    出题器
  • 原文地址:https://www.cnblogs.com/maxiag/p/13479541.html
Copyright © 2011-2022 走看看