Vue项目打包后如何整合到Django

这里记录下 Vue 执行 npm run build 命令生成的文件如何整合到 Django 项目中

版本

  • Vue:3.3.4
  • Vite:4.3.9
  • Django:4.2.3

Django 项目

假设项目名称 mysite、应用名称 polls

mysite/settings.py 文件配置

1
2
3
4
5
6
7
8
9
10
# 本地开发环境中设为True才能载入 static 静态文件
DEBUG = True

INSTALLED_APPS = [
'polls.apps.ApiConfig',
]

STATIC_URL = 'static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

mysite/urls.py 文件配置

1
2
3
urlpatterns = [
path('', include('polls.urls')),
]

polls/views.py 文件配置

1
2
3
4
5
6
7
8
9
10
11
12
from django.http import JsonResponse
from django.shortcuts import render


def index(request):
return render(request, 'polls/index.html')


def vue(request):
if request.method == 'GET':
return JsonResponse({"data": "Hello, I'm Django"})
return JsonResponse({"data": "None"})

polls/urls.py 文件配置

1
2
3
4
5
6
7
8
9
from django.urls import path

from . import views


urlpatterns = [
path('', views.index, name='index'),
path('vue/', views.vue, name='vue'),
]

Vue 项目

vite.config.js 文件配置

新增一个 build 配置项:

1
2
3
4
5
6
7
8
export default defineConfig({

build: {
// js css img 输出目录
assetsDir: 'static/polls',
}

})

App.vue 文件配置

使用 Axios 实现一个 get 请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script>
import axios from 'axios'

export default {
data() {
return {
msg: '',
}
},
methods: {
get() {
axios('vue/')
.then(res => {
this.msg = res.data.data
})
.catch(err => {
this.msg = err
})
}
}
}
</script>

<template>
<div>
<button @click="get">点击获取数据</button>
<h2>Get请求数据:{{ msg }}</h2>
</div>
</template>

构建生产版本

1
npm run dev

应该看到应该 dist 目录:

1
2
3
4
5
6
7
dist
- static
- polls
- index-84a34640.css
- index-079c396d.js
- favicon.ico
- index.html

Django 整合 Vue

dist 目录下的 index-84a34640.cssindex-079c396d.jsfavicon.ico 复制到 Django polls/static/polls/ 目录下

index.html 复制到 polls/templates/polls/ 目录下

启动 Django 服务

1
python manage.py runserver

访问 http://127.0.0.1:8000/ 点击按钮应该看到:

1
Get请求数据:Hello, I'm Django

有一个小问题,ico图标没有显示,修改 polls/templates/polls/index.html

1
2
- <link rel="icon" href="/favicon.ico">
+ <link rel="icon" href="/static/polls/favicon.ico">

重新刷新页面就会显示了