vue django实现登陆
Vue 和 Django 实现登录功能
前端 (Vue.js) 部分
安装 axios 用于 HTTP 请求
npm install axios
创建登录组件
<template>
<div>
<input v-model="username" placeholder="Username">
<input v-model="password" type="password" placeholder="Password">
<button @click="login">Login</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
login() {
axios.post('http://localhost:8000/api/login/', {
username: this.username,
password: this.password
})
.then(response => {
localStorage.setItem('token', response.data.token);
this.$router.push('/dashboard');
})
.catch(error => {
console.error(error);
});
}
}
}
</script>
后端 (Django) 部分
安装 Django REST framework 和简单 JWT
pip install djangorestframework djangorestframework-simplejwt
配置 settings.py
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
创建登录视图

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
class LoginView(APIView):
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user:
refresh = RefreshToken.for_user(user)
return Response({
'refresh': str(refresh),
'access': str(refresh.access_token),
})
return Response({'error': 'Invalid credentials'}, status=400)
配置 URLs
from django.urls import path
from .views import LoginView
urlpatterns = [
path('api/login/', LoginView.as_view(), name='login'),
]
跨域处理 (CORS)
安装 django-cors-headers
pip install django-cors-headers
配置 settings.py

INSTALLED_APPS = [
...
'corsheaders',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
]
前端路由保护
在 Vue 路由中添加导航守卫
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
if (to.matched.some(record => record.meta.requiresAuth) && !token) {
next('/login');
} else {
next();
}
});
后端用户认证
添加认证装饰器到需要保护的视图
from rest_framework.decorators import permission_classes
from rest_framework.permissions import IsAuthenticated
@permission_classes([IsAuthenticated])
class ProtectedView(APIView):
def get(self, request):
return Response({'message': 'Authenticated content'})






