当前位置:首页 > VUE

vue django实现登陆

2026-02-20 15:51:13VUE

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',
    )
}

创建登录视图

vue django实现登陆

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

vue django实现登陆

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'})

标签: vuedjango
分享给朋友:

相关文章

vue实现选区

vue实现选区

Vue 实现选区的基本方法 在Vue中实现选区功能通常涉及DOM操作和事件处理。以下是几种常见的方法: 使用原生JavaScript的Selection API 通过window.getSel…

vue实现截图

vue实现截图

Vue 实现截图的方法 使用 html2canvas 库 安装 html2canvas 库: npm install html2canvas 在 Vue 组件中使用: import html2…

vue实现setinterval

vue实现setinterval

在 Vue 中使用 setInterval Vue 中可以通过生命周期钩子和方法结合 setInterval 实现定时任务。以下是一个完整的实现示例: <template> <…

vue  实现tab

vue 实现tab

实现 Tab 切换功能 在 Vue 中实现 Tab 切换功能可以通过动态组件或条件渲染完成。以下是两种常见方法: 使用 v-if 或 v-show 实现条件渲染 通过绑定 currentTab 变量…

vue实现视频

vue实现视频

Vue 实现视频播放的方法 在 Vue 项目中实现视频播放可以通过多种方式完成,以下是几种常见的方法: 使用 HTML5 的 <video> 标签 在 Vue 组件中直接使用 HTML…

vue实现注册

vue实现注册

Vue 实现注册功能 注册功能通常涉及前端表单、数据验证、与后端 API 的交互等步骤。以下是一个完整的 Vue 实现注册功能的方案。 创建注册表单 使用 Vue 的模板语法创建注册表单,包含用户名…