本文介绍了通过Python Flask服务器提供服务时,Vue应用无法加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个简单的"hello world" VueJS应用程序:

 <!doctype html>< html>< head><元http-equiv ="content-type" content ="text/html; charset = utf-8"/>< script type ="text/javascript" src ="https://unpkg.com/vue"></script></head><身体>< div id ="app">讯息:{{讯息}}</div>< script>var vm = new Vue({el:#app",数据: {讯息:你好,世界"}});</script></body></html> 

当我在浏览器中将该文件加载到本地磁盘(即file:///home/user/vue-project/index.html)上时,它就会加载并显示"Hello,world".>

但是,如果我尝试获取相同的文件并通过python flask开发服务器或gunicorn提供该文件,则{{message}}会变为空白.

有人知道什么可能导致这种情况发生吗?

解决方案

flask使用jinja2渲染其变量,而jinja2使用 {{variable}} 作为其解析定界符

render("mytemplate.html",message ="Hello")将在处理任何javascript之前将所有 {{message}} 块替换为"Hello"...因为您没有定义消息,所以它只是一个空字符串...您将需要配置vue以使用替代定界符(我使用 [[[message]] )

 <!doctype html>< html>< head><元http-equiv ="content-type" content ="text/html; charset = utf-8"/>< script type ="text/javascript" src ="https://unpkg.com/vue"></script></head><身体>< div id ="app">讯息:[[讯息]]</div>< script>var vm = new Vue({el:#app",分隔符:['[[',']]'],数据: {讯息:你好,世界"}});</script></body></html> 

I have a simple "hello world" VueJS app I'm trying to get working:

<!doctype html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
  <div id="app">
    Message: {{ message }}
  </div>
<script>
  var vm = new Vue({
    el: "#app",
    data: {
      message: "Hello, world"
    }
  });
</script>
</body>
</html>

When I load this file in the browser, off my local disk (ie: file:///home/user/vue-project/index.html), it loads and "Hello, world" is displayed.

However, if I try to take the same file and serve it through the python flask development server, or through gunicorn, {{message}} renders blank.

Does anyone know what might be causing that to happen?

解决方案

flask renders its variables with jinja2 which uses {{ variable }} as its parsing delimiter

render("mytemplate.html",message="Hello") would replace all {{ message }} blocks with "Hello" before any javascript is handled ... since you dont define message it is simply an empty string... you will need to configure vue to use alternative delimiters (I use [[ message ]])

<!doctype html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
  <div id="app">
    Message: [[ message ]]
  </div>
<script>
  var vm = new Vue({
    el: "#app",
    delimiters : ['[[', ']]'],
    data: {
      message: "Hello, world"
    }
  });
</script>
</body>
</html>

这篇关于通过Python Flask服务器提供服务时,Vue应用无法加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 07:30