当前位置:首页 > VUE

vue实现登录登出

2026-03-08 19:38:53VUE

Vue 实现登录登出功能

安装依赖

确保项目已安装 Vue 和 Vue Router。若未安装,可通过以下命令安装:

npm install vue vue-router

创建路由配置

src/router/index.js 中配置登录和主页路由:

import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

const routes = [
  { path: '/login', component: Login },
  { path: '/', component: Home, meta: { requiresAuth: true } }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

实现登录页面

src/views/Login.vue 中创建登录表单:

vue实现登录登出

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="username" placeholder="Username" />
    <input v-model="password" type="password" placeholder="Password" />
    <button type="submit">Login</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    handleLogin() {
      // 模拟登录成功
      localStorage.setItem('isAuthenticated', 'true')
      this.$router.push('/')
    }
  }
}
</script>

实现导航守卫

src/router/index.js 中添加全局前置守卫:

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated')
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

实现登出功能

src/views/Home.vue 中添加登出按钮:

vue实现登录登出

<template>
  <div>
    <h1>Welcome</h1>
    <button @click="handleLogout">Logout</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleLogout() {
      localStorage.removeItem('isAuthenticated')
      this.$router.push('/login')
    }
  }
}
</script>

状态管理(可选)

对于复杂应用,建议使用 Vuex 或 Pinia 管理登录状态:

// 使用 Pinia 示例
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isAuthenticated: false
  }),
  actions: {
    login() {
      this.isAuthenticated = true
    },
    logout() {
      this.isAuthenticated = false
    }
  }
})

集成 API 调用

实际项目中需替换模拟登录为真实 API 调用:

methods: {
  async handleLogin() {
    try {
      const response = await axios.post('/api/login', {
        username: this.username,
        password: this.password
      })
      localStorage.setItem('token', response.data.token)
      this.$router.push('/')
    } catch (error) {
      console.error('Login failed', error)
    }
  }
}

安全注意事项

  1. 使用 HTTPS 协议传输敏感数据
  2. 服务端应实现 CSRF 防护
  3. 密码等敏感信息不应明文存储在客户端
  4. 考虑使用 HttpOnly 的 Cookie 存储 token

以上实现提供了完整的登录登出流程,可根据实际需求调整验证方式和状态管理策略。

标签: vue
分享给朋友:

相关文章

vue实现缩放

vue实现缩放

Vue 实现缩放的方法 在 Vue 中实现缩放功能可以通过多种方式完成,以下是一些常见的方法: 使用 CSS transform 属性 通过 CSS 的 transform: scale() 属性可…

vue 实现权限

vue 实现权限

Vue 实现权限控制的方法 在 Vue 项目中实现权限控制通常涉及前端路由、组件和按钮级别的权限管理。以下是几种常见的实现方式: 路由权限控制 通过路由守卫实现权限验证,过滤用户无权访问的路由:…

vue轮询实现

vue轮询实现

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

vue实现login

vue实现login

Vue 实现登录功能 在 Vue 中实现登录功能通常需要以下几个步骤: 创建登录表单组件 在 Vue 项目中创建一个登录表单组件,包含用户名和密码输入框以及提交按钮。可以使用 Vue 的模板语法和双…

vue实现翻页

vue实现翻页

Vue实现翻页功能 在Vue中实现翻页功能通常需要结合分页组件和数据请求逻辑。以下是常见的实现方法: 使用Element UI分页组件 安装Element UI后,可以直接使用其分页组件:…

vue实现keepalive

vue实现keepalive

Vue 中实现 keep-alive 在 Vue 中,keep-alive 是一个内置组件,用于缓存动态组件或组件的状态,避免重复渲染和销毁。以下是实现 keep-alive 的几种方法: 基本用法…