看到报错信息后,了解到是vue-router 3.10版本新增的promise对象,基本上都是说在跳转后加上.catch(() => {})来修正,但是代码修改的工作量比较大。找到了全局修改方法:
在router/index.js中加入下面代码,即可解决, 实测可行
// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
// push
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
// replace
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace= function replace(location) {
return originalReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
很多博客上都只有全局修改push方法的,我们项目里有不少使用replace来做跳转的,所以修改后没有生效。以上这个是比较全的,可以参考使用。
转载地址:https://www.jianshu.com/p/29355ff81f11
不加之前,未登录时,从“我的页面”点击“购物车”则会出现下面情况
加上之后,很丝滑,很nice
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import MyOrder from '@/views/myorder'
import Pay from '@/views/pay'
import Prodetail from '@/views/prodetail'
import Search from '@/views/search'
import SearchList from '@/views/search/list'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'
import store from '@/store'
// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
// push
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
// replace
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
return originalReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
Vue.use(VueRouter)
const routes = [
{ path: '/login', component: Login },
{
path: '/',
component: Layout,
redirect: '/home',
children: [
{ path: '/home', component: Home },
{ path: '/category', component: Category },
{ path: '/cart', component: Cart },
{ path: '/user', component: User }
]
},
{ path: '/myorder', component: MyOrder },
{ path: '/pay', component: Pay },
{ path: '/prodetail/:id', component: Prodetail },
{ path: '/search', component: Search },
{ path: '/searchList', component: SearchList }
]
const router = new VueRouter({
routes
})
const authUrls = ['/pay', '/search', '/cart', '/myorder'] // '/cart'有问题
router.beforeEach((to, from, next) => {
// ...
// console.log(111111111)
// console.log(to, from, next)
// next()
if (!authUrls.includes(to.path)) {
next()
return
}
// console.log('打印token11', store.getters.token)
if (!store.getters.token) {
// console.log('打印token22', store.getters.token)
next('/login')
} else {
next()
}
})
export default router