关于vue路由和路由拦截的一些小问题

// 总的来说两个问题

// 1.路由重复点击报红错误

// 解决方法:重写push方法,cathc掉错误,就不显示了

// 2.路由重复点击栈溢出

// 在beforEach方法里,判断重复路由,就next(false)

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HelloWorld1 from '@/components/HelloWorld1'
import EchartsAll from '@/components/EchartsAll'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/hh/:id',
      // name: 'HelloWorld',
      component: HelloWorld,
      props: true
    },
    {
      path: '/ww',
      name: 'HelloWorld1',
      component: HelloWorld1
    },
    {
      path: '/map',
      name: 'EchartsAll',
      component: EchartsAll
    }
  ]
})

// 总的来说两个问题
// 1.路由重复点击报红错误
// 解决方法:重写push方法,cathc掉错误,就不显示了
// 2.路由重复点击栈溢出
// 在beforEach方法里,判断重复路由,就next(false)
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  console.log(145454545)
  return originalPush.call(this, location)
    // 其实这里没解决掉重复问题,只是trycatch掉了....
    // 去掉catch一样报错
    .catch(err => err)
}
// app.vue里注意,router-link不会触发重复问题
// this.$router.push才能触发
// 之后push方法执行之后,才会接着执行beforeEach方法.....
// 看打印就知道,重复进一个路由的时候
router.beforeEach((to, from, next) => {
  console.log(2454545)
  console.log(to, from)
  // 解决路由栈溢出问题
  // next('/asdfdsa') 不同于next()
  // 这种传参的写法,每次都会触发路由拦截,所以如果不排除
  // 重复的,就会一直栈溢出
  // 所以这里要排除一下重复的
  if (to.path === from.path) {
    next(false)
  } else {
    next()
  }
})
router.onError((error) => {
  console.log('有错误,', error)
})
export default router

关于vue路由和路由拦截的一些小问题_第1张图片

你可能感兴趣的:(关于vue路由和路由拦截的一些小问题)