之前,為了實現router跳轉的每個頁面的url上都帶上addressCode,然后用了一下router攔截器,很好用,當然也可以專門封裝一個方法來實現(跳轉的頁面上帶有addressCode),不過還是感覺router攔截器比較省事。
router攔截器就是在路由跳轉前后,做一些事情,相當於一個鈎子函數。
下面說一下使用方法:
1、在main.js里 引入router
import router from "./router/router";
2、要在 vue實例前寫入
//注冊一個全局前置守衛,確保要調用 next 方法,否則鈎子就不會被 resolved
router.beforeEach((to, from, next) => {
//路由切換時,如果沒有就添加,有就跳過執行,添加固定參數
if (!to.query.addressCode) {
//准備一個跳轉的query對象
let query = to.query
query.addressCode = tool.getAddressCode();//是一個封裝好的獲取addressCode的方法
alert.eduToast('沒'+query.addressCode,6000);//調試代碼
next({
path: to.path,
query: query
})
} else {
if (to.path !== window.location.pathname) {
// 此處不可使用location.replace
window.location.assign(to.fullPath)
} else {
next()
}
alert.eduToast('有',6000);//調試代碼
}
})
