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)

May 09, 2018 am 11:11 AM
javascript Case

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

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
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 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'
})
Copy after login
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'),
Copy after login
Change them to

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

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
Copy after login
To run in a virtual environment (MacOS):

$ source venv/bin/activate
Copy after login

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
Copy after login

Now let us write 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('/')
def index():
return render_template("index.html")
Copy after login

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

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

这将启动本地主机上的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")
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: '/', component: 'Home' },
{ path: '/about', component: 'About' },
{ path: '*', component: 'NotFound' }
]
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('/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")
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 再在

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles