如何将 Vue.js 与 Flask 结合使用? [英] How can I combine Vue.js with Flask?

查看:134
本文介绍了如何将 Vue.js 与 Flask 结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时使用 Vue.js 和 Flask:Vue.js 用于动态前端,Flask 用于后端.我该怎么做?

解决方案

我最近遇到了这个问题(结合 Vue.js 和 Flask).

至少有两种方法可以组合它们,这取决于您是在创建 1) 一个简单的 Vue.js 应用程序还是 2) 一个更复杂的 Vue.js 应用程序,需要使用像 Webpack 这样的模块捆绑器来组合单文件组件或 npm 包.

<小时>

简单的 Vue.js 应用:

这实际上相当简单且非常强大:

  1. 如果您希望 Vue.js 功能(应用")位于其自己的页面上,请创建一个新模板 .html 文件.否则只需打开您希望应用程序所在的任何 .html 模板文件.
    • 这是您的 Vue.js 模板代码所在.
  2. 如果您同意将 Vue.js JavaScript 代码放在与 HTML 相同的文件中,下面是一个简单的Hello World"示例模板,您可以使用它来了解需要包含的内容Flask 模板文件:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script><身体><div id="应用程序"><p>{{消息}}</p>

<脚本>新的 Vue({el: '#app',数据: {消息:你好 Vue.js!"}})

  • 请注意,此示例将 Vue.js JavaScript 代码包含在 Flask 模板文件中,因此您无需单独包含 Vue.js JavaScript.对于较小的项目,这可能更容易.
  • 或者,如果您希望 Vue.js JavaScript 代码位于其自己的文件中:

    1. 在您的 static 文件夹中创建一个新的 JavaScript 文件,以您要创建的应用程序命名.
      • 这是您的 Vue.js JavaScript 代码所在.
    2. .html 模板文件的底部包含一个脚本标记以包含 Vue.js.
      • <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
        • 请注意,该版本号会更改,因此不要只复制该行.您可以在此处获取最新版本的链接.
    3. 同样在该模板文件的底部,包含一个脚本标记来加载您刚刚创建的 JavaScript 文件.
      • <script src="%% url_for('static', filename='js/YOUR_APP_NAME.js') %%"></script>
    4. 在具有 appid.html 模板文件中创建一个新的 div.

  • 如果你使用 Jinja2 来渲染你的模板,你需要添加几行代码来告诉 Jinja2 不要使用 {{ }} 语法来渲染变量,因为我们需要 Vue.js 的那些双花括号符号.以下是您需要添加到 app.py 中以执行此操作的代码:

    class CustomFlask(Flask):jinja_options = Flask.jinja_options.copy()jinja_options.update(dict(variable_start_string='%%', # 默认是 '{{',我改变这个是因为 Vue.js 使用 '{{'/'}}'variable_end_string='%%',))app = CustomFlask(__name__) # 这会替换你现有的app = Flask(__name__)"

    • 请注意,如果您切换 Flask 的语法,Flask-Bootstrap 将无法工作,因为 Flask-Bootstrap 有自己的模板,该模板仍将包含{{"/}}"语法.您可以在此处查看如何更改 Vue.js 的语法,这比更改 Flask 的语法还要简单.
  • 照常提供页面./照常渲染模板文件.
  • 如果您愿意,可以使用 Vue.js 2.0 Hello World JSFiddle 进行一些更快的原型设计,然后将代码复制到您的 .html.js 文件中.
    • 确保小提琴使用的是最新版本的 Vue.js!
  • 简单!

    <小时>

    使用 Webpack 的更复杂的 Vue.js 应用:

    1. 安装 Node(它带有 npm,这是我们需要的).
    2. 安装vue-cli:
      • npm install -g @vue/cli
    3. 创建一个新的 Vue.js Webpack 项目:
      • vue 创建我的项目
      • 一种方法是创建一个 server 文件夹和一个 client 文件夹,其中 server 文件夹包含 Flask 服务器代码,client 文件夹包含 Vue.js 项目代码.
      • 另一种方法是将 Vue.js 项目作为文件夹包含在 Flask 项目中.
    4. 设置您的 Webpack 配置,以便在 Flask server/templates 文件夹中创建 app.html 文件,以及 所需的静态 JavaScript 和 CSSapp.htmlserver/static/app/ 文件夹中创建,与 Flask 应用程序的非 Vue 部分使用的静态资产隔离.
    5. 如果您想将 Vue.js 项目与 Flask 项目合并,请从包含 Vue.js 项目的文件夹中运行 npm run build,这将生成一个 .html 文件和几个静态文件(JavaScript 和 CSS).

    <小时>

    我对 Webpack 配置所做的确切更改(通过我的 git commit):

    client/build/webpack.dev.conf.js:

    new HtmlWebpackPlugin({- 文件名:'index.html',- 模板:'index.html',+ 文件名:'app.html',+ 模板:'app.html',

    这里(上图)我将 Vue.js 'launch' 文件的名称更改为 app.html,这样它就不会与我的 Flask 应用程序的 'index.html' 冲突.

    <小时>

    client/config/index.js:

    module.exports = {建造: {环境:需要('./prod.env'),- 索引:path.resolve(__dirname, '../dist/index.html'),- assetsRoot: path.resolve(__dirname, '../dist'),- 资产子目录:'静态',- assetsPublicPath: '/',+ 索引:path.resolve(__dirname, '../../server/templates/app.html'),+ assetsRoot: path.resolve(__dirname, '../../server/static/app'),+ assetsSubDirectory: '',+ assetsPublicPath: '/static/app',

    在这里(上面)我正在设置 app.html 文件和静态资产的创建位置.

    因为我们指示 Webpack 在 Flask 的静态"文件夹(/static/app/)中生成静态资产...

    1. html 文件中包含这些资源的相对 URL 将被 Webpack 自动正确设置.
      • 例如:src=/static/app/js/app.f5b53b475d0a8ec9499e.js
    2. 当查询这些 URL 上的文件时,Flask 将自动知道如何提供它们,因为它们位于 static/ 文件夹中,Flask 假定该文件夹具有 /static/etc. 网址.
      • 生成的唯一需要 Flask 路由的文件是 app.html 文件.

    <小时>

    client/build/webpack.prod.conf.js:

    new HtmlWebpackPlugin({文件名:process.env.NODE_ENV === '测试'- ?'index.html'+ ?'app.html': config.build.index,- 模板:'index.html',+ 模板:'app.html',

    这里(上面)我只是重命名了启动"页面,与 webpack.dev.conf.js 中的一样.

    <小时>

    routes.py:

    @web_routes.route('/app')@需要登录定义应用程序():如果 current_user.datetime_subscription_valid_until <日期时间.日期时间.utcnow():返回重定向(url_for('web_routes.pay'))返回 render_template('app.html')

    这里(上图)是我的渲染函数.我正在使用 Flask 的蓝图功能 (.route),但您不必这样做.

    I want to use Vue.js and Flask together: Vue.js for a dynamic front-end, and Flask for the back-end. How can I do that?

    解决方案

    I recently had this problem (combining Vue.js and Flask).

    There are at least two ways to combine them, depending on whether you're creating 1) a simple Vue.js app or 2) a more-complicated Vue.js app that needs to use a module bundler like Webpack to combine Single-File Components or npm packages.


    Simple Vue.js app:

    This is actually fairly easy and very powerful on its own:

    1. If you want the Vue.js functionality (the "app") to be on its own page, create a new template .html file. Otherwise just open whatever .html template file you want the app to be in.
      • This is where your Vue.js template code will go.
    2. If you're OK with having your Vue.js JavaScript code in the same file as your HTML, below is a simple "Hello World" example template you can use to get a sense of what needs to be in the Flask template file:

      <head>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
      </head>
      <body>
      <div id="app">
          <p>{{ message }}</p>
      </div>
      <script>
      new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue.js!'
        }
      })
      </script>
      </body>
      

      • Note that this example is including the Vue.js JavaScript code within the Flask template file, so that you don't need to include the Vue.js JavaScript separately. This might be easier for smaller projects.
    3. Alternatively, if you want the Vue.js JavaScript code to be in its own file:

      1. Create a new JavaScript file in your static folder, name it after this app you want to create.
        • This is where your Vue.js JavaScript code will go.
      2. At the bottom of the .html template file include a script tag to include Vue.js.
        • <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
          • Note that that version number will change, so don't just copy that line. You can get the link for the most-recent version here.
      3. Also in that template file, also at the bottom, include a script tag to load the JavaScript file you just created.
        • <script src="%% url_for('static', filename='js/YOUR_APP_NAME.js') %%"></script>
      4. Create a new div in the .html template file that has an id of app.
        • <div id="app"></div>

    4. If you are using Jinja2 to render your templates, you will need to add a few lines of code to tell Jinja2 to not use the {{ }} syntax to render variables, because we need those double-curly-brace symbols for Vue.js. Below is the code you need to add to your app.py to do this:

      class CustomFlask(Flask):
          jinja_options = Flask.jinja_options.copy()
          jinja_options.update(dict(
              variable_start_string='%%',  # Default is '{{', I'm changing this because Vue.js uses '{{' / '}}'
              variable_end_string='%%',
          ))
      
      app = CustomFlask(__name__)  # This replaces your existing "app = Flask(__name__)"
      

      • Note that Flask-Bootstrap will not work if you switch Flask's syntax, as Flask-Bootstrap has its own templates which will still contain the "{{" / "}}" syntax. You can see here how to change Vue.js's syntax, it's even easier than changing Flask's syntax.
    5. Serve the page as usual. / Render the template file as usual.
    6. If you want, use a Vue.js 2.0 Hello World JSFiddle to do some quicker prototyping, and then copy the code over into your .html and .js files.
      • Make sure that the fiddle is using the most-recent version of Vue.js!

    Easy!


    More-complicated Vue.js app using Webpack:

    1. Install Node (it comes with npm, which is what we need).
    2. Install vue-cli:
      • npm install -g @vue/cli
    3. Create a new Vue.js Webpack project:
      • vue create my-project
      • One way to do this is to create a server folder and a client folder, where the server folder contains the Flask server code, and the client folder contains the Vue.js project code.
      • Another way is to have the Vue.js project contained as a folder within your Flask project.
    4. Set up your Webpack config so that the app.html file is created in your Flask server/templates folder, and the static JavaScript and CSS needed by app.html is created in a server/static/app/ folder, isolated from the static assets used by the non-Vue portions of you Flask app.
    5. When you want to combine your Vue.js project with your Flask project, run npm run build from within the folder containing your Vue.js project, which will generate an .html file and several static files (JavaScript and CSS).


    The exact changes I made to my Webpack config (via my git commit):

    client/build/webpack.dev.conf.js:

    new HtmlWebpackPlugin({
    -   filename: 'index.html',
    -   template: 'index.html',
    +   filename: 'app.html',
    +   template: 'app.html',
    

    Here (above) I'm changing the name of the Vue.js 'launch' file to app.html so that it doesn't conflict with my Flask app's 'index.html'.


    client/config/index.js:

    module.exports = {
      build: {
        env: require('./prod.env'),
    -    index: path.resolve(__dirname, '../dist/index.html'),
    -    assetsRoot: path.resolve(__dirname, '../dist'),
    -    assetsSubDirectory: 'static',
    -    assetsPublicPath: '/',
    +    index: path.resolve(__dirname, '../../server/templates/app.html'),
    +    assetsRoot: path.resolve(__dirname, '../../server/static/app'),
    +    assetsSubDirectory: '',
    +    assetsPublicPath: '/static/app',
    

    Here (above) I'm setting where the app.html file and static assets should be created.

    Because we're directing Webpack to generate the static assets within Flask's "static" folder (/static/app/)...

    1. The relative URLs to include those assets within the html file will automatically be set up correctly by Webpack.
      • Ex: src=/static/app/js/app.f5b53b475d0a8ec9499e.js
    2. When queried for the files at those URLs, Flask will automatically know how to serve them since they're within the static/ folder, which Flask assumes has a /static/etc. URL.
      • The only generated file that will need a Flask route is the app.html file.


    client/build/webpack.prod.conf.js:

    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
    -    ? 'index.html'
    +    ? 'app.html'
        : config.build.index,
    -  template: 'index.html',
    +  template: 'app.html',
    

    Here (above) I'm just renaming the 'launch' page, same as in webpack.dev.conf.js.


    routes.py:

    @web_routes.route('/app')
    @login_required
    def app():
        if current_user.datetime_subscription_valid_until < datetime.datetime.utcnow():
            return redirect(url_for('web_routes.pay'))
    
        return render_template('app.html')
    

    Here (above) is my render function. I'm using Flask's Blueprints feature (<blueprint_name>.route) but you don't have to.

    这篇关于如何将 Vue.js 与 Flask 结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆