一、從何處開始
在Vue.js中,router.beforeEach是我們能夠執行在路由改變前的鉤子函數。它能夠用於驗證用戶登錄,許可權判斷,頁面刷新等等。這裡我們將會從多個方面對router.beforeEach進行詳細的闡述。
二、router.beforeEach刷新才觸發
router.beforeEach只有在url進行跳轉刷新時才會觸發。這也就意味著如果是直接網頁選項卡進行的跳轉,是不會觸發router.beforeEach的。這種情況下我們需要使用router-link或者history進行跳轉。下面的示例代碼可以幫助你理解這個問題:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
console.log('router.beforeEach:', to, from)
next()
})
new Vue({
router,
el: '#app',
render: h => h(App)
})
在這種情況下,我們打開瀏覽器的控制台,在選擇不同的報告進行跳轉時,能夠看到router.beforeEach的相應輸出。
三、router.beforeEach()函數寫在哪裡
在Vue.js中,我們可以在router實例化之後的任意時刻添加一個全局的beforeEach路由鉤子函數。我們可以在main.js文件中進行添加:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
// ...其他路由配置
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
// 在這裡寫你的邏輯代碼
})
new Vue({
router
}).$mount('#app')
四、router.beforeEach不執行的原因
下面我們來看一下,為什麼router.beforeEach函數可能會無效:
- 路由傳參時,跳轉時沒有傳遞參數。
- router.beforeEach內部沒有使用next函數,或者使用了多次next函數。
- 路由本身就沒有進行跳轉。
下面的示例代碼可以幫助你進行進一步了解:
router.beforeEach((to, from, next) => {
if (to.path === '/home') {
// 在'/home'頁面,我們不進行路由跳轉
} else {
next()
}
})
五、router.beforeEach執行多次
如果你對router.beforeEach多次執行很困惑,那麼這裡的解釋或許能夠幫助你。
每個router-view組件都會將route信息作為他的prop進行傳遞,所以只要路由發生改變,所有的router-view都會重新執行一次。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/250818.html