怎么在Django中整合Vue项目

发布时间:2021-06-17 11:49:04 作者:小新
来源:亿速云 阅读:464

这篇文章将为大家详细讲解有关怎么在Django中整合Vue项目,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

随着Vue的流行,很多人想要在自己的Django项目中使用Vue,而大多数都是更改Vue的"{{ data }}",来避免与Django的template数据冲突问题。 其实有更好的方法,直接在Django中使用Vue/Cli

  1. 删除Django的templates文件夹

  2. 使用Vue在Django项目下创建一个templates的项目

  3. 在settings.py中修改TEMPLATES

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
  1. 在项目的urls.py中加入

from django.views.generic.base import TemplateView
from django.urls import path, re_path

urlpatterns = [
	path('', TemplateView.as_view(template_name='dist/spa/index.html')),
	re_path('^css/.*$', views.css, name='css'),
	re_path('^js/.*$', views.js, name='js'),
	re_path('^fonts/.*$', views.fonts, name='fonts')
]
  1. 在项目views.py中加入

from django.http import StreamingHttpResponse
from django.conf import settings
from wsgiref.util import FileWrapper
import mimetypes

async def css(request):
    path = str(settings.BASE_DIR) + '/templates/dist/spa' + request.path_info
    content_type, encoding = mimetypes.guess_type(path)
    resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
    resp['Cache-Control'] = "max-age=864000000000"
    return resp

async def js(request):
    path = str(settings.BASE_DIR) + '/templates/dist/spa' + request.path_info
    content_type, encoding = mimetypes.guess_type(path)
    resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
    resp['Cache-Control'] = "max-age=864000000000"
    return resp

def fonts(request):
    path = str(settings.BASE_DIR) + '/templates/dist/spa' + request.path_info
    content_type, encoding = mimetypes.guess_type(path)
    resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
    resp['Cache-Control'] = "max-age=864000000000"
    return resp
  1. 在项目__init__.py中加入

import mimetypes
mimetypes.add_type("text/css", ".css", True)
mimetypes.add_type("text/javascript", ".js", True)

配置说明

这样一套下来,你就可以在templates文件夹里面写vue,在项目文件夹下面写django了,希望这套方案可以完美的解决你们现在遇到的问题。

关于“怎么在Django中整合Vue项目”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. 详解在pycharm中如何创建django项目
  2. 怎么在Django项目中使用JWT

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

django vue

上一篇:ASP.NET Core WebApi怎么动态生成树形Json格式数据

下一篇:.net core日志结构化的含义和用法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》