Search code examples
python-3.xvue.jsweb-frontend

Best practise vue.js frontend and python backend


I want a python script to trigger on-click events of vue.js components. Most ways I've seen, seem to work by a .json for data exchange. Events in the frontend are not directly into script, but update a .json with properties of the used components. Python reads the file and pushes it back.

Since I'm new into everything which involves vue.js, I want to ask what best practise is. Since there also suggestion like going with FastAPI, Django or FLask and let vue.js do the rendering.!

Thanks in advance.


Solution

  • Vue.js is a great Javascript framework to learn, glad you are picking it up!

    There are a few ways to integrate Python with Vue, your Python backend could indeed work by manipulating JSON data. Your Vue.js application would then trigger API requests (GET, POST, etc.) to your Python backend in response to user actions, like click events.

    Let's take an example with Python Flask. We can create a basic API that simply returns some data when a specific route is hit:

    from flask import Flask, jsonify
    
    app = Flask(__name__)
    
    @app.route('/api/data', methods=['GET'])
    def get_data():
        data = {'key': 'value'}
        return jsonify(data)
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Then in your Vue app, you would use an HTTP client like axios to send a GET request to this route when a button is clicked and do something with the response data.

    Install Axios:

    npm install axios
    

    Vue.js:

    <template>
      <button @click="fetchData">Fetch data</button>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      methods: {
        fetchData() {
          axios.get('http://localhost:5000/api/data')
            .then(response => {
              console.log(response.data);
              // do something with response.data
            })
            .catch(error => {
              console.error(error);
            });
        }
      }
    }
    </script>
    

    This way, when the button in this Vue.js component is clicked, it will trigger a GET request to http://localhost:5000/api/data (the Flask server) and log the response data.

    This is a simple example. In a real-world application, you'd want to handle errors properly and probably use Vuex to manage your application's state.