Home > Enterprise >  When using Laravel and Vue, what are the pros and cons of passing data to Vue via Blade Views vs dir
When using Laravel and Vue, what are the pros and cons of passing data to Vue via Blade Views vs dir

Time:12-09

Presently, I pass data from Laravel to Vue (via MySQL DB's) this way:

In routes/web.php:

Route::get('/', [MyController::class, 'index']);

In app/Http/Controllers/MyController.php

public function index() {

    $results = Data::all();

    return view('index', compact('results'));

}

In resources/views/index.blade.php:

<div id="app">
    <index-component :results="{{ $results }}" />
</div>

And then in IndexComponent.vue

props: {
    results: { 
        type: Object 
    };
}

This works well enough but as I've come to rely on Vue for most of my HTML, it feels unnatural and almost like a workaround or hack. There must be a simpler and more direct way?

Enter Axios:

In routes/web.php:

Route::view('/', 'index');
Route::get('/indexrequests', [MyController::class, 'indexRequests']);

In app/Http/Controllers/MyController.php:

public function indexRequests() {

    $results = Data::all();

    return response()->json($results);
}

In resources/views/index.blade.php:

<div id="app">
    <index-component />
</div>

In IndexComponent.vue:

created() {
    this.getResults()
},
data: function() { 
    return {
        results: null,
    }
}, 
methods: {
    getResults() {
          axios
            .get("/indexrequests")
            .then((res) => (this.results = res.data))
            .catch((error) => {});
    }
}
 

This way, the Blade View can be ignored after it's initially created. The getResults() method is talking directly to the Controller.

My question is, at what cost? What, if anything, am I losing out on by not using Blade Views to pass the data? Will I encounter limitations in the amounts or types of data that can be passed this way? Will performance be better or worse one way or the other? Any security concerns?

Perhaps they are identical under the hood and I simply don't realize that fact?

CodePudding user response:

The methods aren't identical but there won't be many practical differences in this case. It may be beneficial to render some markup on server side with initial data for the purpose of SEO, but this doesn't happen here.

Relying on API instead of hard-coded data results in more flexible frontend application.

Depending on the nature and amount of hard-coded data, it may result in slower initial rendering, but faster complete rendering. Hard-coding data in a prop requires to additionally take care of escaping, also results in performance penalty in case parent component is re-rendered. A common way to do this is to provide initial data as global variable instead:

<script>
window.myApp = { someData: '{{$results}}' };
</script>
<div id="app">
...

Where $results is JSON data with escaped quotes (single quotes in this case).

  • Related