当前位置:首页 > VUE

vue实现登录判断

2026-01-18 14:49:53VUE

Vue实现登录判断的方法

在Vue中实现登录判断通常涉及以下几个关键步骤:

使用路由守卫进行全局拦截

在Vue Router中配置全局前置守卫,检查用户登录状态:

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token') // 检查本地存储的token
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login') // 跳转到登录页
  } else {
    next() // 继续导航
  }
})

在路由配置中添加元信息

定义哪些路由需要登录验证:

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

使用Vuex管理登录状态

在store中维护用户登录状态:

const store = new Vuex.Store({
  state: {
    isLoggedIn: false,
    user: null
  },
  mutations: {
    login(state, user) {
      state.isLoggedIn = true
      state.user = user
    },
    logout(state) {
      state.isLoggedIn = false
      state.user = null
    }
  }
})

在登录组件中处理认证

登录成功后更新状态:

methods: {
  async login() {
    try {
      const response = await authService.login(this.username, this.password)
      this.$store.commit('login', response.user)
      localStorage.setItem('token', response.token)
      this.$router.push('/dashboard')
    } catch (error) {
      console.error('Login failed', error)
    }
  }
}

在组件中使用计算属性检查登录状态

在需要登录验证的组件中添加:

computed: {
  isAuthenticated() {
    return this.$store.state.isLoggedIn
  }
}

实现注销功能

清除登录状态和本地存储:

methods: {
  logout() {
    this.$store.commit('logout')
    localStorage.removeItem('token')
    this.$router.push('/login')
  }
}

使用axios拦截器添加认证头

为API请求自动添加认证token:

vue实现登录判断

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

以上方法组合使用可以构建完整的登录验证系统,确保只有认证用户才能访问受保护的路由和资源。

标签: vue
分享给朋友:

相关文章

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

vue 实现列表

vue 实现列表

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

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue 实现$(id)

vue 实现$(id)

在 Vue 中实现类似 jQuery 的 $(id) 功能,可以通过以下几种方式操作 DOM 元素: 使用 ref 属性 Vue 推荐使用 ref 属性来直接访问 DOM 元素或组件实例。在模板中为…

vue递归实现

vue递归实现

vue递归实现方法 在Vue中实现递归组件通常用于树形结构、嵌套菜单等场景。以下是具体实现方式: 使用组件name属性递归 定义一个组件时,通过name属性让组件可以在自身模板中调用自己: <…

vue实现门户

vue实现门户

Vue 实现门户网站的关键步骤 搭建基础框架 使用 Vue CLI 或 Vite 初始化项目,安装 Vue Router 管理多页面路由。门户通常需要响应式布局,可引入 UI 库如 Element P…