隨着默認Vue 2.x安裝,路由器文件位於src/router/index.js
我能夠然後檢查是否需要修改請求並添加任何缺少的查詢參數(修改to
var顯然沒有效果),然後調用next(.. new rout..)
的「重定向」。
缺點:雙打的呼叫路由,因爲它本質上重定向
潛在上升空間:它的工作原理,以及查詢保存邏輯是在同一個地方。
一個警告:在頁面加載時,路由器會觸發並且「from」是一條非常空的路徑(甚至不包括URL中的查詢參數)。因此,我設置了if
語句來驗證是否需要放置查詢參數。
import Vue from 'vue'
import Router from 'vue-router'
// ... All your other components
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Dashboard',
component: Dashboard
},
// ... All your other routes
]
})
router.beforeEach((to, from, next) => {
if (from.query.token && !to.query.token) {
if (to.path === from.path) {
// console.log('Identical routes detected')
return // This is a no-no via the documentation, but a bug in routing to identical routes strips query params, and this prevents that
}
next({path: to.path, query: {token: from.query.token}})
}
next()
})
export default router
爲什麼你需要那個?這真的很奇怪。也許你可以直接使用Vuex來保存這個密鑰(或者其他任何東西) –
你可以在這個頁面的幫助下做到這一點:https://forum.vuejs.org/t/vue-router-programmatically -append-to-querystring/3655/2和'router.beforeEach'導航衛士,doc:https://router.vuejs.org/en/advanced/navigation-guards.html – nicolast
,但它看起來像完美的用例(如果你需要在後端的標籤)或本地存儲(如果你只需要前端的標籤) – nicolast