当前位置:首页 > VUE

vue实现登录认证

2026-01-08 05:24:19VUE

Vue 登录认证实现方法

使用 Vue Router 和 Vuex 管理登录状态

在 Vue 项目中,通常使用 Vue Router 进行路由管理,Vuex 进行状态管理。登录认证的核心是验证用户身份并维护登录状态。

创建 Vuex store 模块管理用户认证状态:

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

const mutations = {
  SET_USER(state, user) {
    state.user = user
    state.isAuthenticated = !!user
  },
  SET_TOKEN(state, token) {
    state.token = token
  },
  LOGOUT(state) {
    state.user = null
    state.token = null
    state.isAuthenticated = false
  }
}

const actions = {
  login({ commit }, { user, token }) {
    commit('SET_USER', user)
    commit('SET_TOKEN', token)
    localStorage.setItem('token', token)
  },
  logout({ commit }) {
    commit('LOGOUT')
    localStorage.removeItem('token')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

实现登录表单组件

创建登录表单组件处理用户输入和提交:

<template>
  <form @submit.prevent="handleSubmit">
    <input v-model="form.username" type="text" placeholder="用户名">
    <input v-model="form.password" type="password" placeholder="密码">
    <button type="submit">登录</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    async handleSubmit() {
      try {
        const response = await axios.post('/api/auth/login', this.form)
        this.$store.dispatch('auth/login', {
          user: response.data.user,
          token: response.data.token
        })
        this.$router.push('/dashboard')
      } catch (error) {
        console.error('登录失败:', error)
      }
    }
  }
}
</script>

配置路由守卫

使用 Vue Router 的导航守卫保护需要认证的路由:

// router/index.js
router.beforeEach((to, from, next) => {
  const isAuthenticated = store.state.auth.isAuthenticated
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  if (requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

持久化登录状态

应用启动时检查本地存储中的 token 并恢复登录状态:

// main.js
const token = localStorage.getItem('token')
if (token) {
  axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
  store.dispatch('auth/checkAuth')
}

添加 HTTP 拦截器

配置 axios 拦截器自动添加认证 token 并处理过期情况:

// utils/axios.js
axios.interceptors.request.use(config => {
  const token = store.state.auth.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

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

实现注销功能

创建注销按钮触发注销操作:

<template>
  <button @click="logout">注销</button>
</template>

<script>
export default {
  methods: {
    logout() {
      this.$store.dispatch('auth/logout')
      this.$router.push('/login')
    }
  }
}
</script>

这种方法提供了完整的登录认证流程,包括状态管理、路由保护、持久化和 HTTP 请求处理。根据具体需求可以进一步扩展,如添加角色权限控制、双因素认证等功能。

vue实现登录认证

标签: vue
分享给朋友:

相关文章

vue循环数组实现

vue循环数组实现

vue循环数组的实现方法 在Vue中循环数组主要通过v-for指令实现,以下是几种常见用法: 基本数组循环 使用v-for指令遍历数组,可以通过(item, index)的语法获取当前项和索引值:…

vue实现头像剪切

vue实现头像剪切

Vue 实现头像剪切的实现方法 使用 vue-cropperjs 库 vue-cropperjs 是一个基于 cropperjs 的 Vue 组件,专门用于图片裁剪。安装方式如下: npm ins…

vue实现多选联动

vue实现多选联动

vue实现多选联动的方法 使用v-model绑定数组 在Vue中,可以通过v-model绑定一个数组来实现多选联动。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue如何实现冒泡

vue如何实现冒泡

Vue 实现冒泡排序 在 Vue 中实现冒泡排序,可以通过数据绑定和响应式特性动态展示排序过程。以下是一个完整的实现示例,包含代码和详细说明。 数据准备 在 Vue 的 data 中定义一个数组作…

vue手动实现弹窗

vue手动实现弹窗

实现弹窗组件的基本结构 在Vue中手动实现弹窗组件,需要创建一个独立的弹窗组件,并通过props控制其显示与隐藏。弹窗组件通常包含遮罩层、内容区域和关闭按钮。 <template>…

vue实现多层评论回复

vue实现多层评论回复

Vue 实现多层评论回复 数据结构设计 多层评论通常采用嵌套结构,每个评论对象包含子评论数组。示例数据结构如下: comments: [ { id: 1, content: '…