[Vuejs]-How do I pass data from PHP Laravel to Vue.js and re-render a Vue.js component when the data changes?

4👍

Are you using Ajax outside of the Vue component? or within it as a method?

I have an example of how I dynamically update the Vue data from within the component itself. I’m not sure how to have external JS update the Vue component directly but I feel this is a good option to look at. I’m using axios instead of Ajax but the principle is the same (Axios is included by default in most Laravel installs past 5.5).

<template>
    <div>
        <div id="reports">
            <!-- Display data -->
            {{ reports }}
        </div>
        <button @click="refreshReports">Refresh</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                endpoint: '/api/MY_ROUTE/'
            };
        },

        props: {
            reports: Object
        },

        methods: {
            // Make Axios call to API endpoint
            refreshReports() {
                // GET version
                axios.get(this.endpoint)
                    .then(({data}) => {
                        this.reports = data.data;
                    });

                // POST version
                axios.post(this.endpoint, {
                    KEY: 'VALUE',
                }).then(({data}) => {
                    this.reports = data.data;
                });

                /*
                    `data.data` assumes the returned response is a JSON Resource

                    if it's not returning the correct data, put a `console.log(data)` and see how it's getting returned!
                 */
            }
        }
    };
</script>

Where in your routes/api.php file you have a route like this:

// GET version
Route::get('MY_ROUTE', 'ReportController@getReports');

// POST version
Route::post('MY_ROUTE', 'ReportController@getReports');

And your Controller would have some method like this:

// app/Http/Controllers/ReportController
public function getReports(Request $request) {
    return Reports::all();
}

Does that make sense?


Update:

I’m not sure how to have external JS update the Vue component directly

I know you can import external JS scripts and use their functions in methods but I’ve never done it that way before.

Something like:

<script>
import { myFunction } from '../external.js'

export default {
    methods: {
        refreshReports() {
            // I have no idea if this is the correct way to do it, just a guess!
            this.reports = myFunction();
        }
    }
};
</script>

Leave a comment