1

我在使用 vue 3 (vue-cli) 和 vue-router 4 在我的应用程序中登录用户时遇到一些问题

这是 router.js

import { createRouter, createWebHistory } from 'vue-router';

import store from '../store';

import AuthLayout from "../layouts/AuthLayout";
import DashboardLayout from "../layouts/DashboardLayout";
import PageNotFound from "../views/errors/PageNotFound";

import Login from "../views/auth/Login";
import Logout from "../views/auth/Logout"
import Dashboard from "../views/dashboard/Dashboard";

let routes = [
  {
    path: '/',
    redirect: 'dashboard',
    component: DashboardLayout,
    children: [
      {
        path: '/',
        component: Dashboard,
        name: 'dashboard',
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/logout',
        component: Logout,
        name: 'logout',
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/:pathMatch(.*)*',
        component: PageNotFound,
        name: 'page-not-found',
        meta: {
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/',
    redirect: 'login',
    component: AuthLayout,
    children: [
      {
        path: '/login',
        component: Login,
        name: 'login',
        meta: {
          requiresVisitor: true
        }
      },
    ]
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: routes,
  linkExactActiveClass: 'active'
});

// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !store.state.authenticated) {
    return {
      name: 'login',
    }
  }
})

export default router;

我在路由中导入商店以访问经过身份验证的状态。当服务器对用户进行身份验证时,则身份验证 = true。

经过身份验证的(来自 vuex 的状态)......现在是真的......但它保持在登录表单。如果我强制进入/(仪表板),它会再次返回登录。

用户已登录。

任何人都知道我在 routes.js 中缺少什么???

***** 更新 *****

登录组件

export default {
  name: "Login.vue",
  setup() {
    const axios = inject('$axios')
    const store = useStore()
    const authenticated = computed(() => store.state.authenticated)

    const auth = ref( {
      email: '',
      password: ''
    })

    const authUser = () => {
      axios.get('/api/user').then(response => {
        store.commit('setAuthenticated',true);
        store.commit('setUser', response.data)
      })
    }

    const handleLogin = () => {
      // eslint-disable-next-line no-unused-vars
      axios.post('/login', auth.value).then(response => {
        authUser()
      }).catch(error => {
        console.log(error)       
      })
    }

    onMounted(() => {
      // eslint-disable-next-line no-unused-vars
      axios.get('/sanctum/csrf-cookie').then(response => {
        authUser()
      })
    })

    return { auth, handleLogin, authenticated }
  }
}
4

1 回答 1

0

我认为,问题在于身份验证状态不是持久的。这意味着,如果您重定向(使用手动 url 更改)或刷新,数据就会消失。

您可以通过添加持久性

const state = {
  authenticated: localStorage.getItem('authenticated')==='true'; // get authentication from local storage
}
const store = createStore({
  state: state,
  mutations: {
    setAuthenticated(state, payload) {
      state.authenticated = payload;
      localStorage.setItem('authenticated', payload); // sill store 'true' in local storage
    }
  }
})

这会将authenticated状态存储在您的 localStorage 中。state.authenticated它在实例化时填充存储值,并在更改时更新。

还有一些其他注意事项,例如重定向

    const authUser = () => {
      axios.get('/api/user').then(response => {
        store.commit('setAuthenticated',true);
        store.commit('setUser', response.data);
        router.push('/'); // <= will redirect after the values are set
      })
    }
于 2021-04-26T21:11:35.897 回答