• Vue跳转相同路由报错


    大家使用Vue做开发的时候应该都遇到过这个问题,就是某个页面下调用this.$router.push(path),而path指向的页面和当前页面是同一页面时,就会发生报错,vue-router会提示你避免跳转到当前页面,报错如下:

    一般情况我们可以在调用this.$router.push之前判断一下,当前页面与path的关系,如果path指向当前页面,就不调用该方法,代码如下:

    // 获取当前页面路径
    let curPath = this.$route.fullPath;
    
    // 判断下当前路由是否就是要跳转的路由
    if (curPath.includes(path)) return;
    
    this.$router.push(path);

    上述做法没有毛病,一般可以解决问题,但是只能在此次调用this.$router.push方法时有效,如果在其他地方也要调用这个方法,就要再写一遍,所以有没有一个一劳永逸的方法呢?

    答案是:有滴~

    我们可以把这个逻辑放到全局去,如在router/index.js页面,可以这么写:

    // 实例化vue-router对象
    const router = new VueRouter({
        routes: [
            // ...
        ]
    })
    
    /** 解决跳转重复路由报错问题 */ 
    const routerPush = router.push;
    router.push = path => {
    // 判断下当前路由是否就是要跳转的路由
    if (router.currentRoute.fullPath.includes(path)) return; return routerPush.call(router, path); }

    export default router

    以上代码其实是利用“函数劫持”实现的,首先用一个变量将router.push方法缓起来,然后重新定义router的push方法,在方法里面判断一下是否真的要调用push,如果不需要就直接返回。(实际上push方法是定义在VueRouter.prototype上的,所以一开始拿到的router.push实际上是VueRouter.prototype对象上的push,所以也不是在router上重新定义push方法,而是直接添加push方法。)

    完。

  • 相关阅读:
    django实现github第三方本地登录
    django扩展User模型(model),profile
    WSGI
    Linux查看配置文件中未被注释的有效配置行
    virsh 命令
    qemu-img命令
    python logging
    oslo.messaging
    集成kafka的身份认证(SASL/PLAIN)到kubernets环境中
    Helm基础知识
  • 原文地址:https://www.cnblogs.com/yuanyiming/p/14473892.html
Copyright © 2020-2023  润新知