当前位置:首页 > VUE

vue路由跳转实现登录

2026-02-22 02:32:09VUE

vue路由跳转实现登录

在Vue中实现登录功能并跳转路由,通常需要结合Vue Router和状态管理(如Vuex或Pinia)。以下是常见的实现方法:

创建登录组件

开发一个登录表单组件,包含用户名和密码输入框以及提交按钮。使用v-model绑定表单数据:

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="username" placeholder="用户名"/>
    <input v-model="password" type="password" placeholder="密码"/>
    <button type="submit">登录</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async handleLogin() {
      // 登录逻辑
    }
  }
}
</script>

配置路由守卫

在路由配置中设置导航守卫,保护需要认证的路由:

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'

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

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

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

export default router

实现登录逻辑

在登录方法中处理认证成功后跳转:

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('/dashboard')
    } catch (error) {
      console.error('登录失败:', error)
    }
  }
}

处理登录状态

使用状态管理存储登录状态,便于全局访问:

// store/auth.js
export const useAuthStore = defineStore('auth', {
  state: () => ({
    isAuthenticated: !!localStorage.getItem('token')
  }),
  actions: {
    login(token) {
      localStorage.setItem('token', token)
      this.isAuthenticated = true
    },
    logout() {
      localStorage.removeItem('token')
      this.isAuthenticated = false
    }
  }
})

响应式导航栏

根据登录状态显示不同导航选项:

<template>
  <nav>
    <router-link to="/">首页</router-link>
    <router-link v-if="!auth.isAuthenticated" to="/login">登录</router-link>
    <button v-else @click="auth.logout">退出</button>
  </nav>
</template>

<script setup>
import { useAuthStore } from '@/stores/auth'
const auth = useAuthStore()
</script>

权限验证API请求

在axios拦截器中添加认证token:

vue路由跳转实现登录

// utils/axios.js
import axios from 'axios'

const instance = axios.create({
  baseURL: '/api'
})

instance.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

export default instance

以上方法实现了Vue应用中的登录功能与路由跳转,包括路由保护、状态管理和API请求认证。根据实际项目需求,可以进一步扩展和完善这些功能。

标签: 跳转路由
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

vue实现动态路由按钮

vue实现动态路由按钮

Vue 实现动态路由按钮的方法 动态路由按钮的实现通常涉及权限控制,根据用户角色或权限动态显示或隐藏路由按钮。以下是几种常见方法: 基于路由元信息(meta)和v-if控制 在路由配置中添加权限标识…

vue 实现登录跳转

vue 实现登录跳转

实现登录跳转的基本流程 在Vue中实现登录跳转通常涉及以下几个核心步骤:路由配置、登录表单处理、状态管理及导航守卫。以下是具体实现方法: 路由配置 在router/index.js中配置登录页和需要…

vue路由怎么实现

vue路由怎么实现

Vue 路由实现方法 Vue 路由通常通过 vue-router 库实现,以下是具体实现步骤: 安装 vue-router 在项目中运行以下命令安装 vue-router: npm install…

vue实现导航跳转

vue实现导航跳转

vue-router 基本跳转方法 在 Vue 项目中实现导航跳转主要通过 vue-router 完成。安装路由依赖: npm install vue-router 在 router/index.j…

php 实现路由

php 实现路由

PHP 实现路由的方法 在 PHP 中实现路由功能可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 PHP 实现简单路由 通过解析 URL 并匹配对应的处理逻辑,可以实现基本的路由功能。以…