Flask and Frontend Frameworks: A Practical Guide to Combining Vue.js with Flask

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:

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

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

  1. Create Flask Project
    In flask_server, create app.py with 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
  1. Start Flask Backend
    In the flask_server directory:
   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

  1. 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
  1. Install Axios (Data Request Tool)
    Vue uses Axios to send HTTP requests to the backend:
   npm install axios --save
  1. Write Vue Component
    Modify src/App.vue for 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

  1. Start Frontend Vue
    In vue_client/my-vue-app:
   npm run serve

The frontend runs at http://localhost:8080.

  1. Verify Data Interaction
    Visit http://localhost:8080 to see the user list:
    - 张三 (20岁)
    - 李四 (22岁)
    - 王五 (25岁)

7. Common Issues & Solutions

  1. 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)
  1. Axios Request Path Error
    Ensure the Axios get URL matches the backend endpoint (e.g., http://localhost:5000/api/users).

  2. Vue Component Not Rendering Data
    Check that v-for uses user.id as :key and userList is initialized as an empty array in data().

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.

Xiaoye