相当于是路由的生命周期函数
假设路由配置实例如下
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) => { // ... })
router.beforeEach((to, from, next) => { console.log('hi'); let token = localStorage.getItem('token') if (to.path == '/order' && !token) { next('/login') } else { next() } })
思路:每次页面跳转时,获取元数据;如果需要验证就验证用户会话是否存在
{ path: "/about", name: "about", component: () => import("@/views/AboutView.vue"), meta: { requiresAuth: true, }, },
const signUp = async () => { isLoading.value = true; let { data, error } = await supabase.auth.signUp({ email: user.value.email, password: user.value.password, options: { data: { name: 'coffee', avatar: '/coffee.jpg', } } }) if (error) { console.log(error); isLoading.value = false; return; } isLoading.value = false; console.log(data); }
const signIn = async () => { isLoading.value = true; let { data, error } = await supabase.auth.signInWithPassword({ email: user.value.email, password: user.value.password }) if (error) { console.log(error); isLoading.value = false; return; } isLoading.value = false; console.log(data); }
router.beforeEach(async (to, from, next) => { if (to.meta.requiresAuth) { console.log("page requiresAuth"); let { data, error } = await supabase.auth.getSession(); if (data.session) { console.log("authenticated"); next(); } else { next({ name: "login" }); } } else { next(); } });
const logOut = async () => { isLoading.value = true; let { error } = await supabase.auth.signOut() if (error) { console.log(error); isLoading.value = false; return; } isLoading.value = false; console.log('log out'); }
封装获取用户会话
router.afterEach((to, from) => { // ... })
//.... 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 } })
{ path: "/mine", name: "mine", component: () => import("../views/MineView.vue"), meta: { showNav: true, title: "我的 - 个人中心" }, },
router.afterEach((to, from) => { window.scrollTo(0, 0); if(to.meta.title){ document.title = to.meta.title } })
router.beforeEach((to, from, next) => { NProgress.start(); next() }) router.afterEach((to, from) => { NProgress.done(); })