Vue 3 Composition API,Vue-router 4导航保护在使用时抛出错误

nwnhqdif  于 2023-01-09  发布在  Vue.js
关注(0)|答案(1)|浏览(134)

当我尝试使用导航警卫从Vue路由器4,我的代码不再工作它显示一个错误与未定义(推)从Pinia商店router.push('/') .这里是我的代码:

import { createRouter, createWebHistory } from "vue-router";
import manageStaffRoutes from "./manage.staff.js";
import authRoutes from "./login.js";

import { useAuthStore } from "@/stores/auth.store.js";

const routes = [...manageStaffRoutes, ...authRoutes];

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
});

router.beforeEach(async (to, from) => {
    const auth = await useAuthStore();
    const publicPages = ["/login", "/super-admin-login"];
    const authRequired = !publicPages.includes(to.path);
    if (authRequired && !auth.user) {
        return "/";
    }
});
export default router;

然后在我的商店我有这个代码,在那里我试图重定向成功登录后的用户

import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";

export const useAuthStore = defineStore("userAuth", () => {
    const router = useRouter();
    const userData = ref(null);
    const errorMessages = ref(null);

    const user = computed(() => {
        return JSON.parse(localStorage.getItem("user"));
    });

    if (user.value) {
        axios.defaults.headers.common["Authorization"] = `${user.value.token}`;
    }

    async function login(email, password) {
        try {
            const data = await axios.post("api/v1/users/login", {
                email: email,
                password: password,
            });
            if (data.status === 200) {
                userData.value = data.data;
                localStorage.setItem(
                    "user",
                    JSON.stringify(userData.value.data)
                );
                await router.push("/"); // the error
               
            }
        } catch (error) {
            console.log(error);
            return (errorMessages.value = error.response.data.errorsToSend);
        }
    }

    const logout = async () => {
        try {
            const data = await axios.post("api/v1/users/logout");
            console.log(data);
            if (data.status === 201) {
                user.value = null;
                localStorage.removeItem("user");
                await router.push({ name: "login" }); // the error
            
            }
        } catch (error) {
            console.log(error);
            // return (errorMessages.value = error.response.data.message);
        }
    };
    return { login, user, errorMessages, logout };
});

下面是错误:

kmpatx3s

kmpatx3s1#

遵循单一责任原则我建议你改变商店的login()函数,删除路由器推送让商店只认证你的用户。这样做的话,重定向是由调用函数而不是登录来处理的。

作者存储

import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";

export const useAuthStore = defineStore("userAuth", () => {

    // .... 

    async function login(email, password) {
        try {
            const data = await axios.post("api/v1/users/login", {
                email: email,
                password: password,
            });

            if (data.status === 200) {
                userData.value = data.data;
                localStorage.setItem(
                    "user",
                    JSON.stringify(userData.value.data)
                );
            }
        } catch (error) {
            console.log(error);
            return (errorMessages.value = error.response.data.errorsToSend);
        }
    }
};

路由器

import { useAuthStore } from "@/stores/auth.store.js";

// ...

router.beforeEach(async (to, from) => {
    const authStore = useAuthStore();
    const publicPages = ["/login", "/super-admin-login"];
    const authRequired = !publicPages.includes(to.path);

    if (authRequired && !auth.user) {
        return "/";
    }
});

相关问题