欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue-router不允許導(dǎo)航到當(dāng)前位置(/path)錯誤原因以及修復(fù)方式

 更新時間:2021年09月16日 11:42:36   作者:rudy_zhou  
本文主要介紹了Vue-router不允許導(dǎo)航到當(dāng)前位置(/path)錯誤原因以及修復(fù)方式,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

報錯提示

Navigating to current location ("/path") is not allowed

Navigating to current location ("/path") is not allowed

錯誤原因

控制臺出現(xiàn)以上這種 Navigating to current location ("/path") is not allowed 時,是因為重復(fù)進入了相同路由。

錯誤演示

為了演示報錯,用vue-cli重新構(gòu)建了一個新的項目,只編寫了一個按鈕一個input。
code:

<!-- vue模板代碼 -->
<div>
	<button @click="gotoHandle">測試路由跳轉(zhuǎn)</button>
	<input v-model="routeName">
<div>
// 路由跳轉(zhuǎn)代碼
export default {
  data() {
    return {
      routeName: ''
    }
  },
  methods: {
    gotoHandle() {
      this.$router.push({name: this.routeName})
    }
  }
}

動圖演示

Navigating to current location ("/path") is not allowed

在重復(fù)進入相同路由時(不論是通過路徑,還是路由名稱進入),會提示不允許導(dǎo)航到當(dāng)前位置(path), 就像上面的例子進入路由名為About的路由時,提示的是path: "/about",Navigating to current location ("/about") is not allowed。這是因為跳轉(zhuǎn)的方法錯誤時,未捕獲錯誤處理,因此直接輸出了錯誤信息。

解決方法

方法一

直接在跳轉(zhuǎn)報錯的那個地方加上.catch(error => error)

export default {
  data() {
    return {
      routeName: ''
    }
  },
  methods: {
    gotoHandle() {
      this.$router.push({name: this.routeName}).catch(error => error)
    }
  }
}

方法二

為跳轉(zhuǎn)錯誤的方法全局加上錯誤捕獲。

import VueRouter from 'vue-router'

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location) {
  return routerPush.call(this, location).catch(error => error)
}

以上代碼在main.js,或者router/index.js 下執(zhí)行,以及new VueRouter之前之后都一樣。因為是重置的VueRouter原型對象上的push事件,給原型對象的push事件添加上了捕獲異常,所以會通過原型鏈改變所有相關(guān)對象。

replace 方法重復(fù)跳轉(zhuǎn)錯誤與上方類似,把push改成replace就好。

方法三

此方法為建議方法,建議優(yōu)化跳轉(zhuǎn)邏輯,避免重復(fù)跳轉(zhuǎn)相同路由。

到此這篇關(guān)于Vue-router不允許導(dǎo)航到當(dāng)前位置(/path)錯誤原因以及修復(fù)方式的文章就介紹到這了,更多相關(guān)Vue-router 導(dǎo)航到當(dāng)前位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論