vue-router 提供的導航鉤子主要用來攔截導航,讓它完成跳轉或取消。
全局鉤子
1、router.beforeEach 注冊一個全局的 before 鉤子:
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
每個鉤子方法接收三個參數:
next(): 進行管道中的下一個鉤子。如果全部鉤子執行完了,則導航的狀態就是 confirmed (確認的)。
next(false): 中斷當前的導航。如果瀏覽器的 URL 改變了(可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到 from 路由對應的地址。
next('/') 或者 next({ path: '/' }): 跳轉到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。
2.afterEach同理,只是不用傳入next函數
示例:一個單頁面應用,返回首頁時,保存其在首頁的瀏覽位置。并且給每一個頁面title賦值
const router = new VueRouter({ base: __dirname, routes }); new Vue({ // eslint-disable-line el: '#app', render: h => h(App), router }); let indexScrollTop = 0; router.beforeEach((route, redirect, next) => { if (route.path !== '/') { indexScrollTop = document.body.scrollTop; } document.title = route.meta.title || document.title; next(); }); router.afterEach(route => { if (route.path !== '/') { document.body.scrollTop = 0; } else { Vue.nextTick(() => { document.body.scrollTop = indexScrollTop; }); } })
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com