当前位置:首页 > VUE

vue实现登陆拦截

2026-02-21 06:30:01VUE

实现登录拦截的方法

在Vue应用中实现登录拦截通常涉及路由守卫和状态管理。以下是几种常见的方法:

使用全局前置守卫

通过router.beforeEach在路由跳转前检查用户登录状态,未登录则重定向到登录页。

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

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

配置路由元信息

在路由配置中添加meta字段标记需要认证的路由。

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

结合Vuex状态管理

使用Vuex存储和检查用户认证状态。

// store/modules/user.js
const state = {
  isAuthenticated: false,
  user: null
}

const mutations = {
  SET_AUTH(state, status) {
    state.isAuthenticated = status
  }
}

处理Token验证

在拦截器中验证JWT等认证Token的有效性。

// axios拦截器
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

登录成功处理

登录成功后更新状态并重定向。

// Login.vue methods
login() {
  auth.login(this.credentials).then(response => {
    localStorage.setItem('token', response.data.token)
    this.$store.commit('SET_AUTH', true)
    this.$router.push(this.$route.query.redirect || '/dashboard')
  })
}

退出登录处理

清除认证信息并重定向到登录页。

vue实现登陆拦截

// Logout.vue
logout() {
  localStorage.removeItem('token')
  this.$store.commit('SET_AUTH', false)
  this.$router.push('/login')
}

注意事项

  • 确保敏感路由都添加了requiresAuth元信息
  • 考虑Token过期时间的处理
  • 实现刷新页面后的状态保持
  • 生产环境应使用HTTPS保护认证信息
  • 后端也需要相应的认证中间件进行双重保护

标签: vue
分享给朋友:

相关文章

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-toa…

vue实现mouseout

vue实现mouseout

Vue 实现 mouseout 事件的方法 在 Vue 中实现 mouseout 事件可以通过多种方式完成,以下是几种常见的方法: 使用 v-on 指令 Vue 提供了 v-on 指令(或简写为 @…

vue监听实现

vue监听实现

Vue 监听实现方法 在 Vue 中可以通过多种方式实现监听数据变化或事件触发,以下是常见的几种方法: 使用 watch 选项 watch 是 Vue 提供的核心功能之一,用于观察和响应 Vue 实…

vue实现popper

vue实现popper

Vue 实现 Popper 的方法 使用 Tippy.js 库 Tippy.js 是一个轻量级的 Popper.js 封装库,提供丰富的工具提示功能。安装 Tippy.js 及其 Vue 封装: n…

vue filter 实现

vue filter 实现

在 Vue.js 中,过滤器(Filter)是一种用于文本格式化的功能,可以在模板中直接使用。以下是实现过滤器的详细方法: 全局过滤器注册 通过 Vue.filter 方法注册全局过滤器,可在所有组…

vue实现增删

vue实现增删

Vue 实现增删功能 在 Vue 中实现增删功能通常涉及数据绑定、事件处理和列表渲染。以下是基于 Vue 2 或 Vue 3 的实现方法: 数据定义 初始化一个数组用于存储列表数据,并在 Vue 实…