当前位置:首页 > 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实现mvc

vue实现mvc

Vue 实现 MVC 模式 Vue 本身是一个 MVVM(Model-View-ViewModel)框架,但可以通过结构调整实现 MVC(Model-View-Controller)模式。以下是具体实…

vue 实现列表

vue 实现列表

Vue 实现列表的方法 在 Vue 中实现列表通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 指令遍历数组,渲染列表项。ite…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…

vue 实现遮罩

vue 实现遮罩

Vue 实现遮罩层的方法 使用固定定位和透明背景 在Vue中实现遮罩层可以通过CSS固定定位结合透明背景色完成。创建一个全屏遮罩组件,利用position: fixed覆盖整个视窗。 <tem…

vue实现日历

vue实现日历

Vue 实现日历的基本方法 使用 Vue 实现日历可以通过自定义组件或借助第三方库完成。以下是两种常见实现方式: 自定义日历组件 创建基于 Vue 的日历组件需要处理日期计算和渲染逻辑。核心是生成当…

vue实现slidedown

vue实现slidedown

Vue 实现 SlideDown 动画效果 在 Vue 中实现 SlideDown 效果可以通过 CSS 过渡或动画结合 Vue 的过渡系统完成。以下是几种常见方法: 使用 Vue Transiti…