在 Pinia 中使用本地存储时路由不起作用

问题描述 投票:0回答:1

使用本地存储后,我的重定向到仪表板的路线突然开始不起作用。它工作然后停止。我不确定到底是什么问题,但我想问题可能是 pinia 中的路由导入问题。

import {defineStore} from "pinia";
import axios from "axios";
import router from "../router";


export const useAuthStore = defineStore("auth", {
    state: () => ({
        errors: {},
        isLoading: false,
        success: {}
    }),
    getters: {
        userToken: () => localStorage.getItem("token"),
        loggedInUser: () => JSON.parse(localStorage.getItem("user")),
    },
    actions: {
        async register(data) {
            try {
                this.isLoading = true;
                await axios.post('/register', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    this.scrollToTop()
                    this.clearAlert();

                });
            } catch (error) {
                console.log(error);
                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.scrollToTop()
                    this.clearAlert();
                }
            }

        },
        async activateAccount(data) {
            try {
                this.isLoading = true
                await axios.post('/activate', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    router.push({name: "login"});
                    this.scrollToTop()
                    this.clearAlert();

                });
            } catch (error) {

                this.isLoading = false;
                if (error.response.status === 500) {
                    this.errors.error = error.response.data.error
                    this.scrollToTop()
                    this.clearAlert();
                }
            }
        },
        async login(data) {
            try {
                this.isLoading = true;
                let res = await axios.post('/login', data);
                this.isLoading = false;
                localStorage.setItem("token", res.data.access_token);
                localStorage.setItem("user", JSON.stringify(res.data.user));
                router.push({name: "dashboard"});

            } catch (error) {
                console.log(error);
                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.scrollToTop()
                    this.clearAlert();
                }
                if (error.response.status === 401) {
                    this.errors.error = error.response.data.error
                    this.scrollToTop()
                    this.clearAlert();

                }
            }
        },
        async logout(token) {
            await axios.get('/logout', {headers: {Authorization: `Bearer ${localStorage.getItem('token')}`}}).then((res) => {
                this.clearLocalStorage();
                router.push({name: "login"})
            });
        },
        async forgotPassword(data) {
            try {
                this.isLoading = true;
                await axios.post('/send-password-reset-code', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    this.scrollToTop()
                    this.clearAlert();
                });
            } catch (error) {
                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.scrollToTop()
                    this.clearAlert();
                }
            }
        },
        async resetPassword(data) {
            try {
                this.isLoading = true;
                await axios.post('/reset-password', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    router.push({name: "login"})
                    this.scrollToTop()
                    this.clearAlert();

                });
            } catch (error) {

                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.scrollToTop()
                    this.clearAlert();
                }

                if (error.response.status === 500) {
                    this.errors.error = error.response.data.error
                    this.scrollToTop()
                    this.clearAlert();
                }
            }
        },
        clearAlert() {
            setTimeout(() => this.errors = {}, 8000);
            setTimeout(() => this.success = {}, 8000);
        },
        scrollToTop() {
            window.scrollTo(0, 0);
        },
        clearLocalStorage() {
            localStorage.setItem("token", '');
            localStorage.setItem("user", {});
        },
    },
});

我的main.js

import {useAuthStore} from "./stores/Authstore";
import './assets/style.css'
import './axios'
import {createApp} from 'vue'
import {createPinia} from 'pinia'

import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(router)
app.use(createPinia())


router.beforeEach((to, from, next) => {

    const authStore = useAuthStore();
    if (to.meta.requiresAuth && !authStore.userToken) {
        next({name: 'login'})
    } else {
        next()
    }
});

app.mount('#app')

我的路线文件

import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'


const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
            meta: {requiresAuth: false},

        },
        {
            path: '/register',
            name: 'register',
            component: () => import('../views/RegistrationView.vue'),
            meta: {requiresAuth: false},

        },
        {
            path: '/activate/:email/:activationCode',
            name: 'activate',
            component: () => import('../views/ActivateAccountView.vue'),
            props: true,
            meta: {requiresAuth: false},

        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/LoginView.vue'),
            meta: {requiresAuth: false},

        },
        {
            path: '/dashboard',
            name: 'dashboard',
            component: () => import('../views/DashboardView.vue'),
            meta: {requiresAuth: true},

        },
        {
            path: '/forgot-password',
            name: 'forgot-password',
            component: () => import('../views/ForgotPasswordView.vue'),
            meta: {requiresAuth: false},

        },
        {
            path: '/reset-password/:email/:passwordResetCode',
            name: 'reset-password',
            component: () => import('../views/ResetPasswordView.vue'),
            props : true,
            meta: {requiresAuth: false},

        },
    ]
})


export default router

其他路由工作正常,但登录路由存在问题。有时登录,有时拒绝。我希望它能无缝运行。

vue.js local-storage vue-router pinia
1个回答
0
投票

我已经将我的商店重构为这个

import {defineStore} from "pinia";
import axios from "axios";
import router from "../router";


export const useAuthStore = defineStore("auth", {
    state: () => ({
        errors: {},
        user: null,
        token: null,
        isLoading: false,
        success: {}
    }),
    getters: {
        userToken: (state) => state.token,
        loggedInUser: (state) => state.user,
    },
    actions: {
        async register(data) {
            try {
                this.isLoading = true;
                await axios.post('/register', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    this.clearAlert();

                });
            } catch (error) {

                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.clearAlert();
                }
            }

        },
        async activateAccount(data) {
            try {
                this.isLoading = true
                await axios.post('/activate', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    router.push({name: "login"});
                    this.clearAlert();

                });
            } catch (error) {

                this.isLoading = false;
                if (error.response.status === 500) {
                    this.errors.error = error.response.data.error
                    this.clearAlert();
                }
            }
        },
        async login(data) {
            try {
                this.isLoading = true;
                await axios.post('/login', data).then((res) => {
                    this.isLoading = false;
                    this.token = res.data.access_token;
                    this.user = res.data.user;
                    router.push({name: "dashboard"})
                });
            } catch (error) {
               console.log(error);
                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.clearAlert();
                }
                if (error.response.status === 401) {
                    this.errors.error = error.response.data.error
                    this.clearAlert();

                }
            }
        },
        async logout(token) {
            await axios.get('/logout', {headers: {Authorization: `Bearer ${token}`}}).then((res) => {
                this.token = null;
                this.user = null;
                router.push({name: "home"})
            });
        },
        async forgotPassword(data) {
            try {
                this.isLoading = true;
                await axios.post('/send-password-reset-code', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    this.clearAlert();
                });
            } catch (error) {
                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.clearAlert();
                }
            }
        },
        async resetPassword(data) {
            try {
                this.isLoading = true;
                await axios.post('/reset-password', data).then((res) => {
                    this.isLoading = false;
                    this.success.message = res.data.message;
                    router.push({name: "login"})
                    this.clearAlert();

                });
            } catch (error) {

                this.isLoading = false;
                if (error.response.status === 422) {
                    this.errors = error.response.data.errors
                    this.clearAlert();
                }

                if (error.response.status === 500) {
                    this.errors.error = error.response.data.error
                    this.clearAlert();
                }
            }
        },
        clearAlert() {
            setTimeout(() => this.errors = {}, 5000);
            setTimeout(() => this.success = {}, 5000);
        }
    },
    persist: {
        enabled: true
    }
});

我的main.js

import {useAuthStore} from "./stores/Authstore";
import './assets/style.css'
import './axios'
import {createApp} from 'vue'
import {createPinia} from 'pinia'
import piniaPersist from 'pinia-plugin-persist'


import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(router)
const pinia = createPinia()
pinia.use(piniaPersist)

app.use(pinia)


router.beforeEach((to, from, next) => {

    const authStore = useAuthStore();

    if (to.meta.requiresAuth && !authStore.userToken) {
        next({name: 'login'})
    } else {
        next()
    }
});

app.mount('#app')

© www.soinside.com 2019 - 2024. All rights reserved.