当前位置:首页 > VUE

vue如何实现登录拦截

2026-01-22 04:39:30VUE

Vue 实现登录拦截的方法

使用路由守卫(Route Guards)

在 Vue 中,可以通过路由守卫(beforeEach)实现登录拦截。路由守卫会在路由跳转前执行,用于检查用户是否已登录。

// router/index.js
import router from './router'
import store from './store'

router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters.isAuthenticated
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

定义路由元信息

在路由配置中,可以通过 meta 字段标记哪些路由需要登录权限。

vue如何实现登录拦截

// router/index.js
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    component: Login
  }
]

结合 Vuex 管理登录状态

使用 Vuex 存储和管理用户的登录状态,确保全局可访问。

// store/index.js
const store = new Vuex.Store({
  state: {
    isAuthenticated: false,
    user: null
  },
  mutations: {
    setAuth(state, payload) {
      state.isAuthenticated = payload.isAuthenticated
      state.user = payload.user
    }
  },
  getters: {
    isAuthenticated: state => state.isAuthenticated
  }
})

登录逻辑实现

在登录组件中,调用登录接口并更新 Vuex 状态,成功后跳转到目标页面。

vue如何实现登录拦截

// Login.vue
methods: {
  async login() {
    try {
      const response = await authService.login(this.form)
      this.$store.commit('setAuth', {
        isAuthenticated: true,
        user: response.user
      })
      const redirect = this.$route.query.redirect || '/'
      this.$router.push(redirect)
    } catch (error) {
      console.error('Login failed:', error)
    }
  }
}

退出登录处理

在退出登录时,清除 Vuex 中的状态并跳转到登录页。

// Logout.vue
methods: {
  logout() {
    this.$store.commit('setAuth', {
      isAuthenticated: false,
      user: null
    })
    this.$router.push('/login')
  }
}

使用导航守卫检查 Token

如果使用 Token 验证,可以在路由守卫中检查 Token 是否有效。

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next('/login')
    } else {
      // 验证 Token 有效性
      verifyToken(token).then(isValid => {
        if (isValid) {
          next()
        } else {
          next('/login')
        }
      })
    }
  } else {
    next()
  }
})

通过以上方法,可以灵活实现 Vue 中的登录拦截功能,确保未登录用户无法访问受保护的路由。

标签: 如何实现vue
分享给朋友:

相关文章

vue卖座网实现

vue卖座网实现

Vue 卖座网实现 项目结构搭建 使用 Vue CLI 快速初始化项目,安装必要依赖如 Vue Router、Vuex、Axios。 创建核心目录结构:components(通用组件)、views(页…

vue实现流程

vue实现流程

Vue 实现流程的基本步骤 安装 Vue.js 可以通过 CDN 引入或使用 npm/yarn 安装。 CDN 方式: <script src="https://cdn.jsdelivr.…

vue实现框架

vue实现框架

Vue 框架实现的核心方法 基础项目搭建 使用 Vue CLI 或 Vite 快速初始化项目。Vue CLI 适合传统项目,Vite 更适合现代轻量级应用。安装后通过命令行工具选择所需配置(如 Rou…

实现 vue 框架

实现 vue 框架

Vue 框架的基本实现 Vue 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是实现 Vue 框架的基本步骤和核心概念。 核心概念 响应式数据绑定 Vue 的核心特性之一是响应式…

vue实现定位

vue实现定位

Vue 中实现定位的方法 在 Vue 中实现定位可以通过以下几种方式: 使用 CSS 定位 通过 CSS 的 position 属性实现定位,Vue 中可以直接在组件的 <style>…

vue 实现fadeout

vue 实现fadeout

Vue 实现淡出效果 在 Vue 中实现淡出(fade-out)效果可以通过 CSS 过渡或动画结合 Vue 的动态渲染功能完成。以下是几种常见方法: 使用 Vue 过渡(Transition)组件…