当前位置:首页 > 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 中):

vue实现登录占用退出

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实现生成二维码

使用qrcode.vue库生成二维码 安装qrcode.vue库: npm install qrcode.vue --save 在Vue组件中使用: <template> <…

vue实现ios

vue实现ios

Vue 实现 iOS 风格应用 使用 Vue 实现 iOS 风格的应用,可以通过结合 UI 框架和自定义样式来达成目标。以下是具体方法和步骤: 选择 iOS 风格的 UI 框架 Vue 生态中有多…

vue实现阻塞

vue实现阻塞

Vue 实现阻塞的方法 在 Vue 中实现阻塞操作通常涉及异步控制、状态管理或生命周期钩子的使用。以下是几种常见方法: 使用 async/await 处理异步阻塞 通过 async/await 可…

vue实现uuid

vue实现uuid

使用 uuid 库生成 UUID 在 Vue 项目中,可以使用 uuid 库来生成 UUID。安装依赖: npm install uuid 在 Vue 组件中使用: import { v4 as…

vue实现计数

vue实现计数

Vue 实现计数功能 在 Vue 中实现计数功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue 数据绑定和事件监听 通过 Vue 的数据绑定和事件监听,可以轻松实现计数功能。以下是一个简…

vue实现左右拉伸

vue实现左右拉伸

实现左右拉伸布局的方法 使用CSS Flexbox布局 Flexbox可以轻松实现左右拉伸的效果。通过设置display: flex和flex-grow属性,可以让元素填充可用空间。 <div…