您好,登錄后才能下訂單哦!
今天小編給大家分享一下vue跳轉(zhuǎn)同一路由報(bào)錯(cuò)如何解決的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。
vue中,如果跳轉(zhuǎn)同一個(gè)頁(yè)面路由,雖不會(huì)影響功能,但是會(huì)報(bào)錯(cuò)
原因:路由的push會(huì)向歷史記錄棧中添加一個(gè)記錄,同時(shí)跳轉(zhuǎn)同一個(gè)路由頁(yè)面,會(huì)造成一個(gè)重復(fù)的添加,導(dǎo)致頁(yè)面的報(bào)錯(cuò)
解決方案:在router的index.js中重寫(xiě)vue的路由跳轉(zhuǎn)push
const originalPush = Router.prototype.push Router.prototype.push = function push(location) { return originalPush.call(this, location).catch(err => err); }
使用編程式路由進(jìn)行跳轉(zhuǎn)時(shí),控制臺(tái)報(bào)錯(cuò),如下所示。
該問(wèn)題存在于Vue-router v3.0之后的版本,由于新加入的同一路徑跳轉(zhuǎn)錯(cuò)誤異常功能導(dǎo)致。
重寫(xiě) $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)多次點(diǎn)擊報(bào)錯(cuò)問(wè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>
以上就是“vue跳轉(zhuǎn)同一路由報(bào)錯(cuò)如何解決”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。