vue实现登录占用退出
Vue 登录、占用(状态管理)及退出功能实现
依赖准备
安装 Vue 和状态管理库(如 Pinia 或 Vuex):
npm install vue pinia
登录功能实现
创建登录表单组件 Login.vue:
<template>
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
</template>
<script setup>
import { ref } from 'vue';
import { useAuthStore } from '@/stores/auth';
const username = ref('');
const password = ref('');
const authStore = useAuthStore();
const handleLogin = async () => {
await authStore.login(username.value, password.value);
};
</script>
状态管理(占用)
使用 Pinia 存储登录状态(创建 stores/auth.js):
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null,
isAuthenticated: false,
}),
actions: {
async login(username, password) {
// 模拟 API 调用
const response = await fakeApiLogin(username, password);
this.user = response.user;
this.isAuthenticated = true;
},
logout() {
this.user = null;
this.isAuthenticated = false;
},
},
});
async function fakeApiLogin(username, password) {
return { user: { username }, token: 'fake-token' };
}
退出功能实现
在导航栏或用户菜单中添加退出按钮:
<template>
<button @click="handleLogout" v-if="authStore.isAuthenticated">
退出登录
</button>
</template>
<script setup>
import { useAuthStore } from '@/stores/auth';
const authStore = useAuthStore();
const handleLogout = () => {
authStore.logout();
// 可选:重定向到登录页
router.push('/login');
};
</script>
路由守卫(可选)
配置路由守卫限制未登录访问(在 router/index.js 中):
import { createRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
const router = createRouter({ ... });
router.beforeEach((to) => {
const authStore = useAuthStore();
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
return { path: '/login' };
}
});
关键点说明
- 状态持久化:如需持久化登录状态,可使用
localStorage或在 Pinia 中配合插件如pinia-plugin-persistedstate。 - API 集成:将
fakeApiLogin替换为实际的后端认证接口(如 Axios 请求)。 - 安全建议:敏感操作(如退出)应向后端发送请求以清除服务端会话。
通过上述步骤可实现完整的登录、状态管理及退出流程。







