当前位置:首页 > 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-model 指令绑定数据,并通过 type="password" 设置输入类型为密码: <template>…

vue表单实现搜索

vue表单实现搜索

实现Vue表单搜索功能 在Vue中实现表单搜索功能通常涉及表单绑定、事件处理和搜索逻辑。以下是具体实现方法: 数据绑定与表单结构 使用v-model实现表单与Vue数据的双向绑定: <tem…

vue实现录音文件播放

vue实现录音文件播放

使用 Vue 实现录音文件播放 准备工作 确保项目中已安装必要的依赖,如 vue-audio-recorder 或原生 Web Audio API。录音文件播放通常涉及录音、存储和播放三个核心环节。…

vue实现打印二维码

vue实现打印二维码

安装二维码生成库 使用 qrcode 或 vue-qrcode 库生成二维码。通过 npm 安装: npm install qrcode vue-qrcode 生成二维码 在 Vue 组…

vue 实现弹幕

vue 实现弹幕

vue 实现弹幕的方法 使用 CSS 动画和动态渲染 在 Vue 中实现弹幕效果,可以通过动态渲染弹幕元素并结合 CSS 动画实现。以下是具体步骤: 数据准备 创建一个数组存储弹幕数据,每条弹幕…

vue实现水印

vue实现水印

Vue 实现水印的方法 使用 CSS 背景图 通过 CSS 的 background-image 和 background-repeat 属性实现水印效果。创建一个包含水印文本的 Canvas,将其转…