Home > Web Front-end > JS Tutorial > body text

Example of using Vue.js and Flask to build a single-page App

亚连
Release: 2018-05-26 17:38:47
Original
1491 people have browsed it

This article mainly introduces an example of using Vue.js and Flask to build a single-page App. I think it is quite good. I will share it with you now and give it as a reference. Let’s take a look together

In this tutorial, we will explain how to connect a vue.js single-page application with the Flask backend.

Generally speaking, if you just want to use the vue.js library through Flask templates, there is no problem. However, there is actually an obvious problem that Jinja (template engine) also uses double braces for rendering like Vue.js, but it is only a passable solution.

I would like a different example. If I need to build a single-page application (the application is composed of a single page, vue-router in HTML5's History-mode and other more useful features) using vue.js, provided by Flask Web Serve? Simply put it should be like this, like this:

Flask serves index.html which contains my vue.js App. For front-end development I use Webpack, which provides all the cool features.

Flask has an API side that I can access from my SPA.

I have access to the API side, even when I'm running Node.js for front-end development.

Sounds interesting? So let's do it like this.

Client

I will use Vue CLI to generate a basic vue.js App. If you haven't installed it yet, run:

$ npm install -g vue-cli
Copy after login

The client and backend code will be split into different folders. Initialize the front-end part to run the trace:

$ mkdir flaskvue
$ cd flaskvue
$ vue init webpack frontend
Copy after login

Through the installation wizard. My setup is:

Vue only builds at runtime.

Install Vue-router.

Use ESLint to check the code.

Select an ESLint standard preset.

Do not try out Karma Mocha for unit testing.

Do not use Nightwatch to build end-to-end tests.

ok, next:

$ cd frontend
$ npm install
# after installation
$ npm run dev
Copy after login

Now you can start installing the

vue.js

application. Let's start by adding some pages. Add

home.vue

and about.vue to the frontend/src/components folder. They are very simple, like this:

// Home.vue
<template>
<p>
<p>Home page</p>
</p>
</template>
Copy after login

and

// About.vue
<template>
<p>
<p>About</p>
</p>
</template>
Copy after login

We will use them Correctly identifies our current location (according to the address bar). Now we need to change the

frontend/src/router/index.js

file to use our new component:

import Vue from &#39;vue&#39;
import Router from &#39;vue-router&#39;
const routerOptions = [
{ path: &#39;/&#39;, component: &#39;Home&#39; },
{ path: &#39;/about&#39;, component: &#39;About&#39; }
]

const routes = routerOptions.map(route => {
return {
...route,
component: () => import(`@/components/${route.component}.vue`)
}

})

Vue.use(Router)
export default new Router({
routes,
mode: &#39;history&#39;
})
Copy after login

If you try Enter

localhost:8080

and localhost:8080/about and you should see the corresponding pages.

We are almost ready to build a project and are able to create a static resource file bundle. Before that, let's redefine the output directories for them. Find the next settings in

frontend/config/index.js

:

index: path.resolve(__dirname, &#39;../dist/index.html&#39;),
assetsRoot: path.resolve(__dirname, &#39;../dist&#39;),
Copy after login

Change them to

index: path.resolve(__dirname, &#39;../../dist/index.html&#39;),
assetsRoot: path.resolve(__dirname, &#39;../../dist&#39;),
Copy after login

So the HTML, CSS, and JS of the /dist folder will be in the same level directory /frontend. Now you can run

$ npm run build

to create a package.

Backend

For the Flask server, I will be using Python version 3.6. Create a new subfolder in

/flaskvue

to store the backend code and initialize the virtual environment:

$ mkdir backend
$ cd backend
$ virtualenv -p python3 venv
Copy after login

In order to run in the virtual environment ( MacOS):

$ source venv/bin/activate
Copy after login

This document needs to be activated in Windows (http://pymote.readthedocs.io/en/latest/install/windows_virtualenv.html) .

Installation in a virtual environment:

(venv) pip install Flask
Copy after login

Now let’s write the code for the Flask server. Create the root directory file run.py:

(venv) cd ..
(venv) touch run.py
Copy after login

Add the next code to this file:

from flask import Flask, render_template
app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")

@app.route(&#39;/&#39;)
def index():
return render_template("index.html")
Copy after login

This code is slightly different from Flask's **"Hello World"** code. The main difference is that we specify the location to store static files and templates in the folder

/dist

to distinguish them from our front-end folder. Run the Flask server in the root folder:

(venv) FLASK_APP=run.py FLASK_DEBUG=1 flask run
Copy after login

This will start the web server on localhost:

localhost:5000

FLASK_APP Server-side startup file, flask_debug = 1 will run in debug mode. If everything is correct, you will see the familiar home page and you have completed setting up Vue.

同时,如果您尝试输入/about页面,您将面临一个错误。Flask抛出一个错误,说找不到请求的URL。事实上,因为我们使用了HTML5的History-Mode在Vue-router需要配置Web服务器的重定向,将所有路径指向index.html。用Flask做起来很容易。将现有路由修改为以下:

@app.route(&#39;/&#39;, defaults={&#39;path&#39;: &#39;&#39;})
@app.route(&#39;/<path:path>&#39;)
def catch_all(path):
return render_template("index.html")
Copy after login

现在输入网址localhost:5000/about 将重新定向到index.html和vue-router将处理路由。

添加404页

因为我们有一个包罗万象的路径,我们的Web服务器在现在已经很难赶上404错误,Flask将所有请求指向index.html(甚至不存在的页面)。所以我们需要处理未知的路径在vue.js应用。当然,所有的工作都可以在我们的路由文件中完成。

在frontend/src/router/index.js添加下一行:

const routerOptions = [
{ path: &#39;/&#39;, component: &#39;Home&#39; },
{ path: &#39;/about&#39;, component: &#39;About&#39; },
{ path: &#39;*&#39;, component: &#39;NotFound&#39; }
]
Copy after login

这里的路径'*'是一个通配符, Vue-router 就知道除了我们上面定义的所有其他任何路径。现在我们需要更多的创造 NotFound.vue 文件在**/components**目录。试一下很简单:

// NotFound.vue
<template>
<p>
<p>404 - Not Found</p>
</p>
</template>
Copy after login

现在运行的前端服务器再次 npm run dev ,尝试进入一些毫无意义的地址例如: localhost:8080/gljhewrgoh 。您应该看到我们的“未找到”消息。

添加API端

我们的 vue.js/flask 教程的最后一个例子将是服务器端API创建和调度客户端。我们将创建一个简单的Api,它将从1到100返回一个随机数。

打开run.py并添加:

from flask import Flask, render_template, jsonify
from random import *

app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")

@app.route(&#39;/api/random&#39;)

def random_number():
response = {
&#39;randomNumber&#39;: randint(1, 100)
}
return jsonify(response)

@app.route(&#39;/&#39;, defaults={&#39;path&#39;: &#39;&#39;})
@app.route(&#39;/<path:path>&#39;)
def catch_all(path):

return render_template("index.html")
Copy after login

首先我导入random库和jsonify函数从Flask库中。然后我添加了新的路由 /api/random 来返回像这样的JSON:

{
"randomNumber": 36
}
Copy after login

你可以通过本地浏览测试这个路径: localhost:5000/api/random。

此时服务器端工作已经完成。是时候在客户端显示了。我们来改变home.vue组件显示随机数:

<template>
<p>
<p>Home page</p>
<p>Random number from backend: {{ randomNumber }}</p>
<button @click="getRandom">New random number</button>
</p>

</template>
<script>
export default {
data () {
return {
randomNumber: 0
}
},

methods: {
getRandomInt (min, max) {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
},

getRandom () {
this.randomNumber = this.getRandomInt(1, 100)
}
},

created () {
this.getRandom()
}

}
</script>
Copy after login

在这个阶段,我们只是模仿客户端的随机数生成过程。所以,这个组件就是这样工作的:

  1. 在初始化变量 randomNumber 等于0。

  2. 在methods部分我们通过 getRandomInt(min, max) 功能来从指定的范围内返回一个随机数, getrandom 函数将生成随机数并将赋值给 randomNumber

  3. 组件方法 getrandom 创建后将会被调用来初始化随机数

  4. 在按钮的单击事件我们将用 getrandom 方法得到新的随机数

现在在主页上,你应该看到前端显示我们产生的随机数。让我们把它连接到后端。

为此目的,我将用 axios 库。它允许我们用响应HTTP请求并用 Json 返回 JavaScript Promise 。我们安装下它:

(venv) cd frontend
(venv) npm install --save axios
Copy after login

打开 home.vue 再在

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!