Home >Web Front-end >JS Tutorial >Vue.js+Flask\detailed explanation of building a single-page APP case (with code)

Vue.js+Flask\detailed explanation of building a single-page APP case (with code)

php中世界最好的语言
php中世界最好的语言Original
2018-05-09 11:11:134336browse

This time I will bring you a detailed explanation of the case of building a single-page APP with Vue.js Flask\(with code). What are the precautions for building a single-page APP with Vue.js Flask\? The following are Let’s take a look at practical cases.

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.

Complete source code, you can find it here:

https://

github.com/oleg-agapov/flask-vue-spa

Customer End

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

$ npm install -g vue-cli

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

Via 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

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>
and

// About.vue
<template>
<p>
<p>About</p>
</p>
</template>

We will use them to correctly identify 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 'vue'
import Router from 'vue-router'
const routerOptions = [
{ path: '/', component: 'Home' },
{ path: '/about', component: 'About' }
]
const routes = routerOptions.map(route => {
return {
...route,
component: () => import(`@/components/${route.component}.vue`)
}
})
Vue.use(Router)
export default new Router({
routes,
mode: 'history'
})
If you try typing

localhost:8080

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

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, '../dist/index.html'),
assetsRoot: path.resolve(dirname, '../dist'),
Change them to

index: path.resolve(dirname, '../../dist/index.html'),
assetsRoot: path.resolve(dirname, '../../dist'),

so the HTML, CSS, and JS of the /dist folder will be in 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
To run in a virtual environment (MacOS):

$ source venv/bin/activate

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

Installation in a virtual environment:

(venv) pip install Flask

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

(venv) cd ..
(venv) touch run.py

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('/')
def index():
return render_template("index.html")

这段代码与Flask的 **“Hello World”**代码略有不同。主要的区别是,我们指定存储静态文件和模板位置在文件夹 /dist ,以便和我们的前端文件夹区别开。在根文件夹中运行Flask服务端:

(venv) FLASK_APP=run.py FLASK_DEBUG=1 flask run

这将启动本地主机上的Web服务器: localhost:5000 上的 FLASK_APP 服务器端的启动文件, flask_debug = 1 将运行在调试模式。如果一切正确,你会看到熟悉的主页,你已经完成了对Vue的设置。

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

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template("index.html")

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

添加404页

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

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

const routerOptions = [
{ path: '/', component: 'Home' },
{ path: '/about', component: 'About' },
{ path: '*', component: 'NotFound' }
]

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

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

现在运行的前端服务器再次 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('/api/random')
def random_number():
response = {
'randomNumber': randint(1, 100)
}
return jsonify(response)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template("index.html")

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

{
"randomNumber": 36
}

你可以通过本地浏览测试这个路径: 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>

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

  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

打开 home.vue 再在