相当于是路由的生命周期函数
. 添加一个导航钩子,每次导航之前被执行
. 使用路由实例 router 注册一个全局前置守卫 beforeEach,执行函数 fn:接收3个参数
| item | desc |
|---|---|
| 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.afterEach((to, from) => {
// ...
})
{
path: "/mall",
name: "mall",
component: () => import("@/views/MallView.vue"),
beforeEnter: (to, from, next) => {
console.log({ to, from, next });
next();
}
}
{
path: "/mall",
name: "mall",
component: () => import("@/views/MallView.vue"),
beforeEnter(to, from, next) {
console.log({ to, from, next });
next();
}
}
//....
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
//这之后可以随意使用Pinia...
{
path: "/mine",
name: "mine",
component: () => import("@/views/MineView.vue"),
meta: { title: "我的 - 个人中心" },
},
router.afterEach((to, from) => {
if(to.meta.title){
document.title = to.meta.title;
window.scrollTo(0, 0);
}
})
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');
}
封装获取用户会话