下面我会详细讲解使用Vue.js和Flask来构建一个单页App的示例,包含两个示例说明。
示例1:使用Vue.js和Flask来搭建前后端分离的Todo应用
前端Vue.js
- 使用Vue CLI创建项目
vue create todo-vue
- 安装axios
npm install axios
- 编写Todo.vue组件
<template>
<div>
<h1>Todo List</h1>
<form @submit.prevent="addTodo">
<input type="text" v-model="newTodoText" placeholder="Add a todo">
<button>Add</button>
</form>
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
todos: [],
newTodoText: '',
};
},
methods: {
async addTodo() {
if (!this.newTodoText) return;
const response = await axios.post('/api/todo', { text: this.newTodoText });
this.todos.push(response.data);
this.newTodoText = '';
},
},
async mounted() {
const response = await axios.get('/api/todo');
this.todos = response.data;
},
};
</script>
后端Flask
- 创建项目
mkdir todo-flask
cd todo-flask
- 创建虚拟环境并激活
python3 -m venv venv
source venv/bin/activate
- 安装Flask和Flask-CORS
pip install Flask Flask-CORS
- 创建Flask应用文件app.py
from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
todos = []
@app.route('/api/todo', methods=['GET'])
def get_todos():
return jsonify(todos)
@app.route('/api/todo', methods=['POST'])
def add_todo():
request_data = request.get_json()
new_todo = {'id': len(todos) + 1, 'text': request_data['text']}
todos.append(new_todo)
return jsonify(new_todo)
if __name__ == '__main__':
app.run(debug=True)
- 运行Flask应用
export FLASK_APP=app.py # Windows为 set FLASK_APP=app.py
flask run
将前后端连接起来
- 修改前端Vue.js中的axios请求地址
axios.defaults.baseURL = 'http://127.0.0.1:5000'; // Flask应用运行地址
- 运行前端Vue.js
npm run serve
- 打开浏览器,访问http://localhost:8080 就可以看到Todo应用了。
示例2:使用Vue.js和Flask来进行用户登陆认证
前端Vue.js
- 使用Vue CLI创建项目
vue create login-vue
- 安装axios和vue-router
npm install axios vue-router
- 编写Login.vue组件
<template>
<div>
<h1>Login</h1>
<form @submit.prevent="login">
<input type="text" v-model="username" placeholder="Username">
<input type="password" v-model="password" placeholder="Password">
<button>Login</button>
</form>
<br>
<div v-if="errorMessage">{{ errorMessage }}</div>
</div>
</template>
<script>
import axios from 'axios';
import { mapState } from 'vuex';
export default {
data() {
return {
username: '',
password: '',
errorMessage: '',
};
},
methods: {
async login() {
const data = { username: this.username, password: this.password };
try {
const response = await axios.post('/api/login', data);
this.$store.commit('setToken', response.data.token);
this.$router.push({ name: 'Home' });
} catch (error) {
this.errorMessage = 'Login failed, please try again!';
console.error(error);
}
},
},
computed: mapState([
'token',
]),
};
</script>
- 编写Home.vue组件
<template>
<div>
<h1>Home</h1>
<div>{{ errorMessage }}</div>
<div v-if="!token">Please Login to access your account!</div>
<div v-if="token">Welcome to your account!</div>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
computed: mapState([
'token',
]),
data() {
return {
errorMessage: '',
};
},
async mounted() {
if (this.token) {
try {
const response = await axios.get('/api/user', {
headers: {
Authorization: `Bearer ${this.token}`,
},
});
console.log(response.data);
} catch (error) {
this.errorMessage = 'Request user information failed!';
console.error(error);
}
}
},
};
</script>
后端Flask
- 安装Flask、Flask-CORS和Flask-JWT-Extended
pip install Flask Flask-CORS Flask-JWT-Extended
- 创建Flask应用文件app.py
from flask import Flask, jsonify, request
from flask_jwt_extended import create_access_token, JWTManager, jwt_required, get_jwt_identity
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
app.config['JWT_SECRET_KEY'] = 'jwt-secret-string' # 自行修改
jwt = JWTManager(app)
users = {
'demo': {'password': 'password'},
}
@app.route('/api/login', methods=['POST'])
def login():
username = request.json.get('username', None)
password = request.json.get('password', None)
if not username or not password:
return jsonify({"msg": "Missing username or password"}), 400
user = users.get(username, None)
if not user or user['password'] != password:
return jsonify({"msg": "Invalid username or password"}), 401
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
@app.route('/api/user', methods=['GET'])
@jwt_required
def get_user():
current_user = get_jwt_identity()
user = {'username': current_user}
return jsonify(user)
if __name__ == '__main__':
app.run(debug=True)
将前后端连接起来
- 修改前端Vue.js中的axios请求地址
axios.defaults.baseURL = 'http://127.0.0.1:5000'; // Flask应用运行地址
- 修改/src/store/index.js文件,添加token状态和其对应的mutations
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
token: null,
},
mutations: {
setToken(state, token) {
state.token = token;
},
},
});
- 修改/src/main.js文件,添加vue-router
import Vue from 'vue';
import App from './App.vue';
import store from './store';
import VueRouter from 'vue-router';
import Home from './components/Home.vue';
import Login from './components/Login.vue';
Vue.config.productionTip = false;
Vue.use(VueRouter);
const routes = [
{ path: '/', redirect: '/home' },
{ path: '/home', name: 'Home', component: Home },
{ path: '/login', name: 'Login', component: Login },
];
const router = new VueRouter({
routes,
});
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app');
- 运行前端Vue.js
npm run serve
- 运行后端Flask
export FLASK_APP=app.py # Windows为 set FLASK_APP=app.py
flask run
- 打开浏览器,访问http://localhost:8080 就可以看到用户登陆认证的应用了。
至此,我们就成功地使用Vue.js和Flask来构建了一个单页App和一个用户登陆认证的应用。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用Vue.js和Flask来构建一个单页的App的示例 - Python技术站