相当于是路由的生命周期函数
假设路由配置实例如下
const router = createRouter({ ... })
使用 router.beforeEach 注册一个全局前置守卫,执行函数 fn:接收3个参数:
to:进入的路由
from:离开的路由
next():是一个函数,表示是否允许,实现路由控制,如:未登录不允许访问,并引导|重定向到指定页面
router.beforeEach((to, from, next) => { next() })
router.beforeEach((to, from,) => { })
router.beforeEach((to, from, next) => { if(to.path=='/order') next(false) })
router.beforeEach((to, from, next) => { if (to.path == '/order') { next({ name: 'home' }) } else { next() } })
router.beforeEach((to, from, next) => { console.log('hi'); })
router.beforeEach((to, from, next) => { console.log('hi'); let token = localStorage.getItem('token') if (to.path == '/order' && !token) { next('/login') } else { next() } })
router.afterEach((to, from) => { // })
router.afterEach((to, from) => { if(to.meta.title){ document.title = to.meta.title } })
router.beforeEach((to, from, next) => { NProgress.start(); next() }) router.afterEach((to, from) => { NProgress.done(); })
//.... import { createPinia } from 'pinia' const pinia = createPinia() app.use(pinia) //这之后可以随意使用Pinia...
"getActivePinia()" was called but there was no active Pinia.
import { useMenuStore } from '@/stores/menu' router.beforeEach((to, from, next) => { // 其它逻辑 // MUST const store = useMenuStore(); store.flag = false; next(); }) router.afterEach((to, from) => { // 其它逻辑 if (to.path === from.path) { const store = useMenuStore() store.flag = false } })