当前位置:首页 > VUE

vue router实现登录

2026-03-28 18:52:27VUE

Vue Router 实现登录功能

在 Vue.js 项目中,使用 Vue Router 实现登录功能通常涉及路由守卫、状态管理和权限控制。以下是具体实现方法:

安装依赖 确保项目中已安装 vue-router 和状态管理库(如 vuexpinia)。

npm install vue-router pinia

路由配置router/index.js 中配置路由,标记需要认证的路由。

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: { requiresAuth: true }
  }
]

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

状态管理 使用 Pinia 存储用户认证状态。

vue router实现登录

// stores/auth.js
import { defineStore } from 'pinia'

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

路由守卫 实现全局前置守卫检查认证状态。

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  if (requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    next('/dashboard')
  } else {
    next()
  }
})

登录组件 创建登录页面处理用户凭证。

vue router实现登录

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

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()
const form = ref({
  email: '',
  password: ''
})

const handleLogin = async () => {
  try {
    await authStore.login(form.value)
    router.push('/dashboard')
  } catch (error) {
    console.error('Login failed:', error)
  }
}
</script>

API 集成 在实际项目中,需要将登录请求发送到后端 API。

actions: {
  async login(credentials) {
    const response = await axios.post('/api/login', credentials)
    this.isAuthenticated = true
    this.user = response.data.user
  }
}

退出登录 实现注销功能并重定向。

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

持久化登录状态 使用 localStorage 或 cookie 保持登录状态。

// 登录成功后
localStorage.setItem('token', response.data.token)

// 初始化时检查
if (localStorage.getItem('token')) {
  this.isAuthenticated = true
}

这些步骤展示了 Vue Router 实现登录功能的核心流程,可以根据具体需求进行调整和扩展。

标签: vuerouter
分享给朋友:

相关文章

实现 vue ssr

实现 vue ssr

Vue SSR 实现方法 Vue SSR(Server-Side Rendering)通过服务器端渲染 Vue 应用,提升首屏加载速度和 SEO 友好性。以下是核心实现方法: 基础配置 安装必要依赖…

vue实现主页

vue实现主页

Vue 实现主页的基本步骤 创建一个 Vue 主页通常涉及以下几个关键步骤,从项目初始化到页面布局和功能实现。 初始化 Vue 项目 使用 Vue CLI 或 Vite 初始化项目。Vue CLI…

vue 实现拖拽

vue 实现拖拽

Vue 实现拖拽功能 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。 <template> &l…

vue实现menu

vue实现menu

Vue 实现 Menu 的方法 使用 Element UI 的 Menu 组件 Element UI 提供了现成的 Menu 组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用…

vue实现阻塞

vue实现阻塞

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

vue实现单击

vue实现单击

Vue 实现单击事件的方法 在 Vue 中实现单击事件可以通过 v-on 指令或简写的 @ 符号绑定事件处理器。以下是几种常见的实现方式: 基础用法 通过 v-on:click 或 @click 绑…