vue跳轉(zhuǎn)同一路由報錯的問題及解決
vue跳轉(zhuǎn)同一路由報錯
vue中,如果跳轉(zhuǎn)同一個頁面路由,雖不會影響功能,但是會報錯

原因:路由的push會向歷史記錄棧中添加一個記錄,同時跳轉(zhuǎn)同一個路由頁面,會造成一個重復(fù)的添加,導(dǎo)致頁面的報錯
解決方案:在router的index.js中重寫vue的路由跳轉(zhuǎn)push
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err);
}編程式路由跳轉(zhuǎn)多次點擊報錯問題
使用編程式路由進(jìn)行跳轉(zhuǎn)時,控制臺報錯,如下所示。

問題分析
該問題存在于Vue-router v3.0之后的版本,由于新加入的同一路徑跳轉(zhuǎn)錯誤異常功能導(dǎo)致。
解決方法
重寫 $router.push 和 $router.replace 方法,添加異常處理。
//push
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
return VueRouterPush.call(this, to).catch(err => err)
}
//replace
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (to) {
return VueRouterReplace.call(this, to).catch(err => err)
}
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue 編程式路由跳轉(zhuǎn)多次點擊報錯問題</title>
</head>
<body>
<div id="app">
<button @click="pageFirst">Page First</button>
<button @click="pageSecond">Page Second</button>
<router-view></router-view>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script>
const First = { template: '<div>First Page</div>' } //調(diào)用路由name屬性
const Second = { template: '<div>Second Page</div>' }
routes = [
{ path:'/first', name:"first" ,component: First }, //設(shè)置路由name屬性
{ path: '/second', name:"second", component: Second }
]
router = new VueRouter({
routes
})
//push
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
return VueRouterPush.call(this, to).catch(err => err)
}
//replace
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (to) {
return VueRouterReplace.call(this, to).catch(err => err)
}
const app = new Vue({
router,
methods: {
pageFirst(){ router.push('/first') },
pageSecond(){ router.push({ name: 'second' }) },
},
}).$mount('#app')
</script>
</body>
</html>
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue-quill-editor 自定義工具欄和自定義圖片上傳路徑操作
這篇文章主要介紹了vue-quill-editor 自定義工具欄和自定義圖片上傳路徑操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
詳解vue-router數(shù)據(jù)加載與緩存使用總結(jié)
這篇文章主要介紹了詳解vue-router數(shù)據(jù)加載與緩存使用總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
vuex 多模塊時 模塊內(nèi)部的mutation和action的調(diào)用方式
這篇文章主要介紹了vuex 多模塊時 模塊內(nèi)部的mutation和action的調(diào)用方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

