django - 使用 django 开发和部署 Vuejs 应用程序

标签 django vue.js vuejs2

我在 Vuejs 中构建了一个相当简单的网络应用程序,它使用默认的 npm run dev 命令与 webpack 一起运行。 Vue 应用程序正在使用来自 Django 的 API我使用 django-rest-framework 构建的.每当 Vue 应用程序发生变化时,它都会自动热重新加载,这非常棒。

现在我想使用 django 而不是 webpack 来运行 Vue 应用程序。我的意思是 Django 将使用 html 模板文件进行响应,而 Vuejs 应用程序将在该 html 文件上运行单页应用程序。

我现在做的是首先运行这个命令:

npm run build

然后我将 dist/static/ 文件夹文件复制到 django static 文件夹中。最后将其加载到模板中:

index.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
    ...
    ...
    <link href="{% static "css/app.e446b60204fec1f9f5510c711523ffca.css" %}" rel=stylesheet>
</head>
<body>
<div id="app"></div>

<script src="{% static "js/manifest.88376ea5d07804f39ff7.js" %}"></script>
<script src="{% static "js/vendor.e0e5105739e9947a23e7.js" %}"></script>
<script src="{% static "js/app.571e9140518a5bae898c.js" %}"></script>
</body>
</html>

现在,如果我需要更改 Vue 应用程序,我必须重新构建它,复制文件并将其加载到模板中,这看起来相当冗长。

所以,我希望有更好、更快捷的方法来混合使用 Django 和 Vuejs。

最佳答案

这里有一篇很棒的文章解释了如何在 django 模板中运行 Vue 应用程序。

https://ariera.github.io/2017/09/26/django-webpack-vue-js-setting-up-a-new-project-that-s-easy-to-develop-and-deploy-part-1.html

它几乎解释了如何使用 vue-cli 提供的最新 Vue 应用程序模板来运行所有内容。使用的其他包是 django-webpack-loader 以在模板中呈现 js 包,以及 webpack-bundle-tracker 以允许在 django 应用程序中进行热模块替换。

您可以尝试设置 webpack/django 静态文件以从任何位置运行 vue 应用程序,并将静态文件构建到适合您目的的任何位置。

我采取的另外一个步骤是编写一个自定义模板标记来将 render_bundle 函数包装在 django-webpack-loader 中。要在使用 webpack 进行生产构建后提供应用程序,您需要包括:

{% render_bundle 'manifest' %}
{% render_bundle 'vendor' %}
{% render_bundle 'app' %}

这会在从 webpack 开发服务器提供应用程序时抛出错误。捕获该异常将允许它静默失败,并且您可以利用开发服务器的所有优势进行开发。例如。

from webpack_loader import utils
from webpack_loader.exceptions import WebpackBundleLookupError
from django.utils.safestring import mark_safe

@register.simple_tag
def render_bundle(bundle_name, extension=None, config='DEFAULT', attrs=''):
    try:
        tags = utils.get_as_tags(bundle_name, extension=extension, config=config, attrs=attrs)
    except WebpackBundleLookupError as e:
        return''
    return mark_safe('\n'.join(tags))

关于django - 使用 django 开发和部署 Vuejs 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863458/

相关文章:

javascript - 重绘Highchart系列方法。 Vue.js

typescript - VS Code 中 Vuex 商店的 Intellisense

python - Django + Django REST csrf on AJAX direfent 站点请求

django - 跨 Django 项目共享数据库

vue.js - 在 vue 3 : createElement is not a function 中使用 vue-chartjs

laravel - 如何使用 Laravel Mix 将 Vue block 文件放入 public/js 中?

python - Django Shell 图片上传_io.BufferedReader 无属性大小

带有多个查找参数的 django-rest-framework 自定义 View 集检索

javascript - 选择其他选择下拉菜单的选项

vuejs2 - VueJS 未在 IE11 中呈现