Combining Flask with Vue.js: From Environment Setup to Data Interaction¶
1. Why Choose Flask + Vue.js?¶
In web development, frontend-backend separation is the mainstream architecture. Flask, a lightweight Python backend framework, handles data processing and business logic. Vue.js, a frontend framework, focuses on page rendering and user interaction. Their combination enables:
- Backend: Focus on data processing; Frontend: Focus on user experience.
- High development efficiency with independent collaboration between front-end and back-end teams.
- Flexible data interaction via APIs.
2. Development Environment Setup¶
To start, install the following tools:
-
Python & Flask:
- Install Python (3.6+ recommended): Python Official Website
- Install Flask:pip install flask
- Install CORS tool (to resolve cross-origin issues):pip install flask-cors -
Node.js & Vue.js:
- Install Node.js (with npm): Node Official Website
- Install Vue CLI (for quick project creation):npm install -g @vue/cli
3. Project Structure Design¶
Adopt a front-backend separation structure with two folders in the project root:
my-fullstack-app/
├─ flask_server/ # Backend Flask project
│ └─ app.py # Main Flask file
└─ vue_client/ # Frontend Vue project
└─ my-vue-app/ # Vue project (created via Vue CLI)
4. Backend Flask Setup¶
- Create Flask Project
Inflask_server, createapp.pywith a simple backend API:
from flask import Flask, jsonify
from flask_cors import CORS # Resolve cross-origin issues
app = Flask(__name__)
CORS(app) # Allow all cross-origin requests (for development)
# Mock data: User list
users = [
{"id": 1, "name": "张三", "age": 20},
{"id": 2, "name": "李四", "age": 22},
{"id": 3, "name": "王五", "age": 25}
]
# Backend API: Get user list
@app.route('/api/users', methods=['GET'])
def get_users():
return jsonify(users) # Return JSON data
if __name__ == '__main__':
app.run(port=5000, debug=True) # Run backend on port 5000
- Start Flask Backend
In theflask_serverdirectory:
python app.py
After successful startup, visit http://localhost:5000/api/users to see the user list JSON data returned by the backend.
5. Frontend Vue Setup¶
- Create Vue Project
In the project root:
vue create vue_client/my-vue-app
Select default configuration (or manually choose Vue 3). Enter the project directory:
cd vue_client/my-vue-app
- Install Axios (Data Request Tool)
Vue uses Axios to send HTTP requests to the backend:
npm install axios --save
- Write Vue Component
Modifysrc/App.vuefor data fetching and rendering:
<template>
<div class="container">
<h1>User List</h1>
<ul v-if="userList.length">
<li v-for="user in userList" :key="user.id">
{{ user.name }} ({{ user.age }} years old)
</li>
</ul>
<p v-else>Loading...</p>
</div>
</template>
<script>
import axios from 'axios' // Import Axios
export default {
name: 'App',
data() {
return {
userList: [] // Store user list from backend
}
},
created() { // Execute after component creation
this.fetchUsers() // Call method to get user list
},
methods: {
async fetchUsers() { // Simplify async requests with async/await
try {
// Call backend API (Flask address + port + endpoint)
const response = await axios.get('http://localhost:5000/api/users')
this.userList = response.data // Assign backend data to userList
} catch (error) {
console.error('Request failed:', error)
}
}
}
}
</script>
<style scoped>
.container {
width: 80%;
margin: 50px auto;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 10px;
border: 1px solid #eee;
margin: 5px 0;
}
</style>
6. Run and Test¶
- Start Frontend Vue
Invue_client/my-vue-app:
npm run serve
The frontend runs at http://localhost:8080.
- Verify Data Interaction
Visithttp://localhost:8080to see the user list:
- 张三 (20岁)
- 李四 (22岁)
- 王五 (25岁)
7. Common Issues & Solutions¶
- Cross-Origin Issue
If you encounter “Access to XMLHttpRequest” errors, configure CORS in Flask:
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Allow all cross-origin requests (for development only)
-
Axios Request Path Error
Ensure the AxiosgetURL matches the backend endpoint (e.g.,http://localhost:5000/api/users). -
Vue Component Not Rendering Data
Check thatv-forusesuser.idas:keyanduserListis initialized as an empty array indata().
8. Summary¶
Through this practical exercise, we combined Flask (backend) and Vue.js (frontend):
- Backend: Flask provides a simple API returning JSON data.
- Frontend: Vue renders pages and fetches data via Axios.
- Data interaction: HTTP protocol for communication between frontend and backend.
This separation mode (“backend for logic, frontend for interaction”) improves efficiency and user experience. Future extensions: add CRUD operations, routing, etc.
Extension: Deploy the backend to a cloud server (e.g., Aliyun) and package the frontend with Nginx for production deployment.