这是继上一篇手搓RSS阅读器之后,出于对阅读器进行简单的管理,增加了“偏好设置”,以便于管理订阅的种子和阅读统计功能。 所有设置功能都在同一个页面内如下,
要实现这个功能,就绕不开登录与授权。
前端
-
增加 pinia 组件userStore.js。
import { defineStore } from 'pinia'; export const useAuthStore = defineStore('auth', { state: () => ({ token: localStorage.getItem('userToken') || null, userName: localStorage.getItem('userName') || null, }), getters: { isAuthenticated: (state) => !!state.token, }, actions: { setlogin(token, username) { this.token = token; this.userName = username; localStorage.setItem('userToken', token); localStorage.setItem('userName', username); }, setlogout() { this.token = null; this.userName = null; localStorage.removeItem('userToken'); localStorage.removeItem('userName'); } } });
-
增加路由。
import { createRouter, createWebHistory } from 'vue-router'; import AppLayout from '@/components/AppLayout.vue'; import AdminDashboard from '@/components/AdminDashboard.vue'; import LoginPage from '@/components/LoginPage.vue'; import { useAuthStore } from '@/stores/userStore'; const routes = [ { path: '/', component: AppLayout, }, { path: '/login', component: LoginPage, }, { path: '/admin', component: AdminDashboard, meta: { requiresAuth: true }, } ]; const router = createRouter({ history: createWebHistory(), routes, }); router.beforeEach((to, from, next) => { try { const authStore = useAuthStore(); if (to.meta.requiresAuth && !authStore.isAuthenticated) { next('/login'); } else { next(); } } catch (error) { console.error("Error fetching data:", error); } }); export default router;
-
增加登录,这里手误坑了自己一把,GPT给的代码,手动删掉submit后 prevent后,导致 页面不停的重复提交。 router.beforeEach一直在login里跳不出来
<form @submit.prevent ="handleLogin">
- 在Admin里引用ADD与EDIT的共同子页面。GPT没有给出框架默认控制显示/隐藏切换.
export default {
props: {
isEditing: {
type: Boolean,
default: false
},
entity: {
type: Object,
default: () => ({})
},
isVisible: {
type: Boolean,
default: false // Control visibility from the parent
}
},
后端
在登录接口返回JWT的token后。然后CRUD接口的增加 [Authorize] 属性,自动验证授权。