
Combining Vue.js with Flask creates a powerful full-stack web application. Flask serves as the backend, handling data processing, authentication, and API endpoints, while Vue.js provides a reactive and dynamic frontend. This guide walks through setting up a full-stack web app using Vue.js and Flask.
- Why Use Vue.js with Flask?
Using Vue.js and Flask together offers several benefits:
- Lightweight and Efficient: Flask is a micro-framework with minimal overhead, and Vue.js is optimized for a fast frontend.
- Separation of Concerns: Flask handles backend logic, while Vue.js manages the user interface.
- Flexibility: Vue.js allows for easy integration with other frameworks or libraries.
- REST API Communication: Flask’s API routes seamlessly integrate with Vue.js, enabling dynamic content rendering.
- Setting Up Flask as the Backend
Step 1: Install Flask
pip install flask flask-cors
Step 2: Create a Flask App
mkdir backend
cd backend
nano app.py
Step 3: Write a Basic Flask API
Modify app.py:
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Enable Cross-Origin Resource Sharing
@app.route(‘/api’, methods=[‘GET’])
def home():
return jsonify({“message”: “Hello from Flask API!”})
if __name__ == ‘__main__’:
app.run(debug=True)
Step 4: Run the Flask Server
python app.py
Your API should now be accessible at http://127.0.0.1:5000/api.
- Setting Up Vue.js as the Frontend
Step 1: Create a Vue.js App
npm create vue@latest frontend
cd frontend
npm install
Step 2: Install Axios for API Requests
npm install axios
Step 3: Fetch Data from Flask API
Modify src/App.vue:
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script>
import axios from ‘axios’;
export default {
data() {
return {
message: ”
};
},
mounted() {
axios.get(‘http://127.0.0.1:5000/api’)
.then(response => {
this.message = response.data.message;
})
.catch(error => console.error(‘Error fetching data:’, error));
}
};
</script>
Step 4: Start the Vue.js Application
npm run dev
Your Vue.js app should now display “Hello from Flask API!” fetched from the backend.
- Connecting Flask and Vue.js in Production
For deployment, configure Flask to serve Vue.js by building the Vue app and placing the files in Flask’s static directory.
Step 1: Build the Vue.js App
npm run build
Step 2: Modify Flask to Serve Vue Files
Modify app.py:
from flask import Flask, send_from_directory
import os
app = Flask(__name__, static_folder=’frontend/dist’)
@app.route(‘/’)
def serve_vue():
return send_from_directory(‘frontend/dist’, ‘index.html’)
if __name__ == ‘__main__’:
app.run()
Step 3: Run Flask with Vue.js Integration
python app.py
Now, Flask will serve the Vue.js application along with its API.
Conclusion
By combining Flask’s lightweight backend with Vue.js’ reactive frontend, you can create a powerful full-stack web application. This approach keeps the backend and frontend modular, scalable, and easy to maintain. 🚀