当前位置:首页 > VUE

vue实现登录登出

2026-01-16 06:13:48VUE

Vue 实现登录登出功能

登录功能实现

创建登录表单组件,包含用户名和密码输入框,以及提交按钮。使用v-model双向绑定数据。

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

在Vue组件中定义数据和方法处理登录逻辑。通常需要调用API验证用户凭证。

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

状态管理

使用Vuex管理用户登录状态,创建auth模块存储用户信息和登录状态。

vue实现登录登出

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

const mutations = {
  SET_USER(state, user) {
    state.user = user
    state.isAuthenticated = !!user
  }
}

const actions = {
  login({ commit }, userData) {
    return axios.post('/api/login', userData)
      .then(response => {
        commit('SET_USER', response.data.user)
        localStorage.setItem('token', response.data.token)
      })
  }
}

路由守卫

配置路由守卫保护需要认证的路由,未登录用户尝试访问时重定向到登录页。

// router.js
router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters['auth/isAuthenticated']
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

登出功能实现

创建登出方法清除本地存储的token和Vuex中的用户状态。

vue实现登录登出

methods: {
  handleLogout() {
    localStorage.removeItem('token')
    this.$store.commit('auth/SET_USER', null)
    this.$router.push('/login')
  }
}

在导航栏或适当位置添加登出按钮。

<button @click="handleLogout">登出</button>

持久化登录状态

应用初始化时检查本地存储的token,自动恢复登录状态。

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

API拦截器

配置axios拦截器自动为请求添加认证头,并在收到401响应时自动登出。

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) {
      store.commit('auth/SET_USER', null)
      localStorage.removeItem('token')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

标签: vue
分享给朋友:

相关文章

vue实现用户信息表

vue实现用户信息表

Vue 实现用户信息表的方法 使用 Vue CLI 创建项目 安装 Vue CLI 并初始化项目: npm install -g @vue/cli vue create user-info-tabl…

vue调用接口实现退出

vue调用接口实现退出

实现Vue退出功能的步骤 在Vue中调用接口实现退出功能通常需要与后端API交互,以下是实现方法: 前端实现 创建退出方法,调用后端API接口: methods: { logout() {…

vue实现生成二维码

vue实现生成二维码

使用qrcode.vue库生成二维码 安装qrcode.vue库: npm install qrcode.vue --save 在Vue组件中使用: <template> <…

vue实现边框

vue实现边框

Vue 实现边框的方法 在 Vue 中实现边框效果可以通过多种方式完成,包括内联样式、CSS 类绑定、动态样式以及使用第三方 UI 库。以下是几种常见的实现方法。 内联样式绑定 使用 Vue 的 :…

vue实现发表

vue实现发表

Vue 实现发表功能 在 Vue 中实现发表功能通常涉及表单处理、数据绑定和网络请求。以下是实现步骤和代码示例: 表单设计与数据绑定 创建一个表单用于输入发表内容,使用 v-model 进行数据双向…

vue实现后退

vue实现后退

Vue 实现后退功能的方法 在 Vue 中实现后退功能通常可以通过以下几种方式完成,具体取决于应用场景和需求。 使用 window.history API 通过原生 JavaScript 的 win…