当前位置:首页 > 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 字段标记哪些路由需要登录权限。

// 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 状态,成功后跳转到目标页面。

// 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 是否有效。

vue如何实现登录拦截

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 中实现文字显示可以通过多种方式,包括插值表达式、指令、组件等。以下是几种常见的实现方法: 插值表达式 使用双大括号 {{ }} 进行文本插值,这是 Vue…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue轮询实现

vue轮询实现

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

vue 实现流程

vue 实现流程

Vue 实现流程 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是 Vue 实现的基本流程: 安装 Vue.js 通过 CDN 引入或使用 npm/yarn 安装:…

vue实现tree

vue实现tree

Vue 实现 Tree 组件 使用 Vue 实现 Tree 组件可以通过递归组件的方式来实现层级结构展示。以下是一个完整的实现方法: 基础递归组件实现 创建 Tree 组件文件 Tree.vue,使…

vue 实现评分

vue 实现评分

Vue 实现评分功能 在 Vue 中实现评分功能可以通过多种方式完成,包括使用第三方组件库或自定义实现。以下是两种常见的方法: 使用第三方组件库(如 Element UI) Element UI 提…