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)多次點擊報錯問題
使用編程式路由進行跳轉(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如何實現(xiàn)跨頁面?zhèn)鬟f與接收數(shù)組并賦值
這篇文章主要介紹了vue如何實現(xiàn)跨頁面?zhèn)鬟f與接收數(shù)組并賦值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04Vue用v-for給循環(huán)標簽自身屬性添加屬性值的方法
這篇文章主要介紹了Vue用v-for給循環(huán)標簽自身屬性添加屬性值的方法,文中大家給大家列舉了三種方法 ,需要的朋友可以參考下2018-10-10vue如何使用router.meta.keepAlive對頁面進行緩存
這篇文章主要介紹了vue如何使用router.meta.keepAlive對頁面進行緩存問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05vue iview多張圖片大圖預(yù)覽、縮放翻轉(zhuǎn)
這篇文章主要為大家詳細介紹了vue iview多張圖片大圖預(yù)覽、縮放翻轉(zhuǎn),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07