【问题标题】:How to render Vue with Django如何使用 Django 渲染 Vue
【发布时间】:2021-05-10 10:08:33
【问题描述】:

我正在 Digitalocean 上使用 Vue.js 和 Django 开发一个小型应用程序,所以我还安装了 Django Webpack 加载器和跟踪器,现在我已经执行了我的 Django 服务器 和我的 vue。 js 也使用 npm run serve 并且当我访问我的网页 localhost:8000 时,我只看到一个空白页面,因为一切都已正确安装,这是我的 HTML 页面(当我在 chrome 浏览器上检查时)

<html>
    <head>
            <title>Title of the document</title>  
    </head>
    
    <body>
        
            <div id="app"></div>
    
        <script type="text/javascript" src="http://0.0.0.0:8080/js/app.js"></script>
        
    </body>
    
 </html>

PS:我认为问题出在 app.js 中(因为我点击了链接,但我得到了一个错误)

This site can’t be reachedThe webpage at http://0.0.0.0:8080/js/app.js might be temporarily down or it may have moved permanently to a new web address.
ERR_ADDRESS_INVALID

【问题讨论】:

    标签: django vue.js


    【解决方案1】:

    您应该首先创建 vue.config.js 文件来配置您的 vue 应用程序。 vue.config.js:

    const BundleTracker = require("webpack-bundle-tracker");
    
    module.exports = {
      // on Windows you might want to set publicPath: "http://127.0.0.1:8080/"
      publicPath: "http://0.0.0.0:8080/",
      outputDir: "./dist/",
    
      chainWebpack: (config) => {
        config
          .plugin("BundleTracker")
          .use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
    
        config.output.filename("bundle.js");
    
        config.optimization.splitChunks(false);
    
        config.resolve.alias.set("__STATIC__", "static");
    
        config.devServer
          // the first 3 lines of the following code have been added to the configuration
          .public("http://127.0.0.1:8080")
          .host("127.0.0.1")
          .port(8080)
          .hotOnly(true)
          .watchOptions({ poll: 1000 })
          .https(false)
          .disableHostCheck(true)
          .headers({ "Access-Control-Allow-Origin": ["*"] });
      }
    
      // uncomment before executing 'npm run build'
      // css: {
      //     extract: {
      //       filename: 'bundle.css',
      //       chunkFilename: 'bundle.css',
      //     },
      // }
    };
    

    然后从 webpack_loader 加载 render_bundle。您的 django 模板将如下所示:

    {% load render_bundle from webpack_loader %}
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <!-- This part is in the screenshot at the bottom! -->
        <h1>Vue JS</h1>
        <div id="app"></div>
        {% render_bundle 'app' %}
      </body>
    </html>
    

    确保您使用的是 @0.4.3 版本的 webpack-bundle-tracker

    您可以关注this link获取分步教程。

    【讨论】:

    • 如何加载我的 javascript 文件和 CSS
    • 你可以在django模板上加载css和js。你也可以在 vue 端添加 css 和 js
    猜你喜欢
    • 2020-03-24
    • 2021-04-24
    • 2021-07-06
    • 2021-09-15
    • 2019-11-05
    • 2019-10-08
    • 1970-01-01
    • 2018-05-11
    • 2017-04-26
    相关资源
    最近更新 更多