vue登录如何实现的
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')
}
}






