当前位置:首页 > VUE

vue登录如何实现的

2026-02-22 13:12:07VUE

Vue 登录功能实现步骤

前端部分(Vue.js)

创建登录表单组件,包含用户名和密码输入框,以及提交按钮。使用 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>

<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>

后端部分(Node.js/Express)

创建登录接口,验证用户凭据并返回 JWT 令牌。

const express = require('express')
const jwt = require('jsonwebtoken')
const app = express()

app.post('/api/login', (req, res) => {
  const { username, password } = req.body
  // 实际项目中应从数据库验证用户
  if (username === 'admin' && password === '123456') {
    const token = jwt.sign({ username }, 'your-secret-key', { expiresIn: '1h' })
    res.json({ token })
  } else {
    res.status(401).json({ error: '用户名或密码错误' })
  }
})

路由守卫

在 Vue 路由中设置全局前置守卫,保护需要认证的路由。

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

状态管理(Vuex)

使用 Vuex 管理用户认证状态。

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

HTTP 拦截器

设置 axios 拦截器,自动在请求头中添加认证令牌。

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

注销功能

实现用户注销功能,清除本地存储和状态。

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

vue登录如何实现的

标签: 如何实现vue
分享给朋友:

相关文章

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue实现遮罩

vue实现遮罩

Vue 实现遮罩层的方法 在 Vue 中实现遮罩层可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-show 或 v-if 控制显示 通过 Vue 的指令动态控制遮罩层的显示与隐…

vue实现引导

vue实现引导

Vue 实现引导功能的方法 使用第三方库 推荐使用 driver.js 或 intro.js 这类专门为 Vue 设计的引导库。这些库提供了完整的 API 和样式,能够快速实现引导功能。 安装 d…

vue实现全景

vue实现全景

Vue 实现全景效果的方法 使用 Vue 实现全景效果通常需要结合第三方库或框架,以下是几种常见的方法: 使用 Three.js 和 Vue-Three.js Three.js 是一个强大的 3D…

vue实现骰子

vue实现骰子

Vue 实现骰子功能 创建 Vue 组件 在 Vue 项目中创建一个骰子组件,例如 Dice.vue。该组件包含骰子的外观和逻辑。 <template> <div class…

vue实现编辑

vue实现编辑

Vue 实现编辑功能 在 Vue 中实现编辑功能通常涉及表单绑定、状态管理和事件处理。以下是一个常见的实现方法: 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定: <i…