无需Django Rest Framework,如何将Vite与Vue整合到Django项目?
Django + Vite + Vue 无DRF 实现方案
完全可以让这套技术栈正常运行,核心思路是让Django负责路由、模板渲染和后端逻辑,Vite作为Vue的构建工具直接通过模板关联两者,无需依赖DRF。以下是具体实现步骤:
1. 项目结构搭建
在Django项目根目录下创建Vite+Vue前端项目:
npm create vite@latest frontend -- --template vue cd frontend npm install
最终项目结构示例:
your-django-project/ ├── your_django_app/ ├── static/ ├── templates/ │ └── base.html ├── frontend/ │ ├── src/ │ │ ├── main.js │ │ └── App.vue │ └── vite.config.js └── manage.py
2. 配置Vite输出路径
修改frontend/vite.config.js,让打包后的资源输出到Django的static/vue目录,并生成资源清单用于生产环境定位:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], server: { port: 5173, cors: true // 允许Django请求Vite开发服务器资源 }, build: { outDir: '../static/vue', // 输出到Django静态资源目录 assetsDir: 'assets', manifest: true // 生成资源映射清单 } })
3. 关联Django模板与Vue应用
在Django的基础模板(如templates/base.html)中,区分开发/生产环境引入Vue资源:
{% load static %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> {% if DEBUG %} <!-- 开发环境:直接引用Vite开发服务器资源 --> <script type="module" src="http://localhost:5173/@vite/client"></script> <script type="module" src="http://localhost:5173/src/main.js"></script> {% else %} <!-- 生产环境:通过manifest.json加载打包后的资源 --> {% get_static_prefix as static_prefix %} <script id="vite-manifest" type="application/json" src="{% static 'vue/manifest.json' %}"></script> <script> fetch('{% static 'vue/manifest.json' %}') .then(res => res.json()) .then(manifest => { // 加载主JS文件 const appScript = document.createElement('script'); appScript.type = 'module'; appScript.src = `${static_prefix}vue/${manifest['src/main.js'].file}`; document.head.appendChild(appScript); // 加载关联CSS if (manifest['src/main.js'].css) { const appCss = document.createElement('link'); appCss.rel = 'stylesheet'; appCss.href = `${static_prefix}vue/${manifest['src/main.js'].css[0]}`; document.head.appendChild(appCss); } }); </script> {% endif %} </head> <body> <div id="app"></div> <!-- Vue应用挂载节点 --> {% block content %}{% endblock %} </body> </html>
4. 开发与运行流程
- 启动Django开发服务器:
python manage.py runserver - 启动Vite开发服务器:
cd frontend npm run dev - 访问Django的任意路由,Vue应用会自动挂载到页面的
#app节点上。
5. Django向Vue传递数据(无需API)
如果需要从Django后端给Vue传数据,直接在模板中注入全局变量即可:
{% block content %} <script> window.__INITIAL_DATA__ = {{ your_context_data|safe }}; </script> {% endblock %}
然后在Vue组件中直接使用:
<script setup> const initialData = window.__INITIAL_DATA__; </script>
6. 生产部署
- 打包Vue资源:
cd frontend npm run build - 收集Django静态文件(确保
settings.py中配置了正确的静态文件目录):python manage.py collectstatic - 启动Django生产服务器(如Gunicorn)即可。
内容的提问来源于stack exchange,提问作者Raji Muhammad
相关产品推荐
相关产品推荐

