vue axios实现登录源码
以下是一个基于Vue.js和Axios实现登录功能的完整示例代码,包含前端和后端交互逻辑:
前端部分(Vue组件)
安装Axios依赖:
npm install axios
登录组件(Login.vue):
<template>
<div class="login-container">
<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>
<p v-if="error" class="error">{{ error }}</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
form: {
username: '',
password: ''
},
error: ''
}
},
methods: {
async handleSubmit() {
try {
const response = await axios.post('/api/login', this.form);
localStorage.setItem('token', response.data.token);
this.$router.push('/dashboard');
} catch (err) {
this.error = err.response?.data?.message || '登录失败';
}
}
}
}
</script>
<style scoped>
.login-container {
max-width: 300px;
margin: 0 auto;
}
.error {
color: red;
}
</style>
后端API示例(Node.js Express)
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
app.use(bodyParser.json());
const users = [
{ id: 1, username: 'admin', password: 'admin123' }
];
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);
if (user) {
const token = jwt.sign({ userId: user.id }, 'your-secret-key', { expiresIn: '1h' });
return res.json({ token });
}
res.status(401).json({ message: '无效的用户名或密码' });
});
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
Axios全局配置
在main.js中添加:
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000';
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
Vue.prototype.$http = axios;
路由守卫
在router/index.js中添加:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
const token = localStorage.getItem('token');
if (!token) {
next({ path: '/login' });
} else {
next();
}
} else {
next();
}
});
这个实现包含以下关键点:
- 前端表单数据绑定和提交处理
- Axios的POST请求发送
- JWT令牌的存储和后续请求的自动附加
- 基本的错误处理
- 路由守卫保护需要认证的页面
可以根据实际需求调整用户验证逻辑、错误处理方式和UI样式。







