zoukankan      html  css  js  c++  java
  • vue-router重写push方法,解决相同路径跳转报错,解决点击菜单栏打开外部链接

    修改vue-router的配置文件,默认位置router/index.js

    import Vue from 'vue'
    import Router from 'vue-router'
     
     
    /**
     * 重写路由的push方法
     * 解决,相同路由跳转时,报错
     * 添加,相同路由跳转时,触发watch (针对el-menu,仅限string方式传参,形如"view?id=5")
     */
     
    // 保存原来的push函数
    const routerPush = Router.prototype.push  
    // 重写push函数
    Router.prototype.push = function push(location) {
     
      // 这个if语句在跳转相同路径的时候,在路径末尾添加新参数(一些随机数字)
      // 用来触发watch
      if(typeof(location)=="string"){
        var Separator = "&";
        if(location.indexOf('?')==-1) { Separator='?'; }
        location = location + Separator + "random=" + Math.random();
      }
     
      // 这个语句用来解决报错
      // 调用原来的push函数,并捕获异常
      return routerPush.call(this, location).catch(error => error)
    }
     
     
    Vue.use(Router)
     
    export default new Router({
      routes: [
        {
          path: '/',
       
        }
      ]
    })
    / 如果你的改了push还是没有生效,可以考虑改replace方法
    // 修改路由replace方法,阻止重复点击报错
    const originalReplace = VueRouter.prototype.replace;
    VueRouter.prototype.replace = function replace(location) {
      return originalReplace.call(this, location).catch(err => err);
    };

    vue解决点击菜单栏跳转外部链接

    const VueRouterPush = Router.prototype.push
    Router.prototype.push = function push (location) {
        console.log(location)
        let user = ''
        if(window.sessionStorage.getItem('user')){
            user = JSON.parse(window.sessionStorage.getItem('user')).roles[0].roleName
        }
        console.log(typeof(location))
        if(typeof(location) == "string"){
            if(location.indexOf('http') == 0){
                if(user == '超级权限'){
                    var Separator = "&";
                    if(location.indexOf('?')==-1) { Separator='?';}
                    location = location + '#/login' + Separator + 'key=123456';
                    window.open(location)
                }else{
                    location = location + '#/login';
                    window.open(location)
                }
            }else{
                return VueRouterPush.call(this, location).catch(err => err)
            }
        }else{
            return VueRouterPush.call(this, location.path).catch(err => err)
        }
    }
    如果真的不知道将来要做什么,索性就先做好眼前的事情。只要今天比昨天过得好,就是进步。长此以往,时间自然会还你一个意想不到的未来。
    生活像一个杯子。一开始,里面是空的,之后,要看你怎么对待它。如果你只往不如意的方面想,那么你最终辉得到一杯苦水。如果你往好的方面想,那么你最终会得到一杯清泉。
    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
  • 相关阅读:
    not syncing: Attempted to kill init
    PhpStudy如何开启Apache的gzip压缩功能?
    去掉桌面图标快捷箭头
    PS中10种样式操作
    Mysql数据库报错1264
    宝塔建站
    VB错误说明
    Flash的swf文件破解
    PS快捷键
    Mysql双向同步热备份设置
  • 原文地址:https://www.cnblogs.com/lipengze/p/14898204.html
Copyright © 2011-2022 走看看