当前位置:首页 > VUE

vue实现登录占用退出

2026-02-24 15:55:16VUE

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 请求)。
  • 安全建议:敏感操作(如退出)应向后端发送请求以清除服务端会话。

通过上述步骤可实现完整的登录、状态管理及退出流程。

vue实现登录占用退出

标签: vue
分享给朋友:

相关文章

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 sl…

vue轮询实现

vue轮询实现

Vue 轮询实现方法 在 Vue 中实现轮询可以通过以下几种方式: 使用 setInterval data() { return { pollInterval: null } }…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue 实现树状

vue 实现树状

Vue 实现树状结构的方法 递归组件实现树状结构 递归组件是 Vue 中实现树状结构的常见方法。通过组件自身调用自身,可以轻松构建多层级树状结构。 <template> <u…

vue 简单实现

vue 简单实现

以下是 Vue 的简单实现示例,涵盖基础模板、数据绑定、方法及生命周期: 基础模板与数据绑定 <div id="app"> <p>{{ message }}</p…

vue nexttick 实现

vue nexttick 实现

Vue nextTick 实现原理 Vue 的 nextTick 是一个用于在下次 DOM 更新循环结束之后执行延迟回调的方法。它主要用于确保在 DOM 更新完成后执行某些操作。 核心实现机制 n…