重复点击路由,导致提示避免到当前位置的冗余导航该怎么解决

import Vue from 'vue'

import VueRouter from 'vue-router'

import Home from '../views/Home/Home.vue'

import Recommend from '../views/Recommend/Recommend.vue'

import Me from '../views/Me/Me.vue'

import Chat from '../views/Chat/Chat.vue'

import Search from '../views/Search/Search.vue'

//  这里按照网上的方法加入了以下代码,但是还是不管用

const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {

 return originalPush.call(this, location).catch(err => err)

}

Vue.use(VueRouter)

const routes = [

 {

 path: '/',

 redirect: '/home'

 },

 {

 path: '/home',

 component: Home,

 children: [

 { path: '/recommend', component: Recommend },

 { path: '/search', component: Search },

 { path: '/me', component: Me },

 { path: '/chat', component: Chat }

 ]

 }

]

const router = new VueRouter({

 routes

})

export default router

这是我的代码,我在按照网上提示,加入了
`const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {

return originalPush.call(this, location).catch(err => err)

}`
但是还是报一样的错误,是我加点位置有问题吗?

阅读 4.5k
2 个回答

这段代码没问题,你先确定一下是不是报的这个错误NavigationDuplicated
image.png

解决这个报错的关键是this.$router.push(...).catch(err => err)要有后面的catch。因为跳转方法返回了一个promise对象,要有处理拒绝的方法。

你添加的这段代码,相当于覆写了一下push方法,统一添加了处理拒绝。调用push应该没问题。

然后你在检查一下,路由跳转的时候是不是调用的push方法,是不是用的replace
如果是就也覆写一下

const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
    return originalReplace.call(this, location).catch(err => err)
}

你在哪里加的 放到index.js

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题