Reputation: 508
I decided to create a little project using Laravel 5.1, vueJS (with vue-resource) and some file interaction on the server-side.
Everything works fine but in the process of creating the app I questioned myself what the best way of receiving data from the server was. Besides the ovious solution, AJAX, I tried writing the data with laravel-blade inside the data object of my Vue instance, which looked like this:
FileController.php:
$files = Auth::user()->files;
return view('files.index', compact('files'));
The files() function is just a simple belongsToMany() relationship on the User Model with a pivot table in the background.
index.blade.php:
new Vue({
el: '#files',
data: {
// pass the data to Vue via PHP so you don't need an AJAX request
files: {!! $files !!}
// ..
}
The other solution would be something like this in my Vue instance:
ready: function() {
this.$http.get('/todos', function (data) {
this.$set('todos', data);
}).error(function (data) {
console.log(data);
});
Now my question is whether or not my approach has any disadvantages because in my opinion it's better because it's less AJAX interaction and that means the app should be faster (at least in theory).
Edit: of course it's possible to simply write it with a blade foreach for example but I want to do the presentation of the data in vue.
Upvotes: 4
Views: 3712
Reputation: 192
You need props
So your element will look like:
<div id="#files" :files="{!! $files !!}"></div>
And your Vue:
new Vue({
el: '#files',
props: {
files: {
type: Object // <- not necessary, you can also have props: ['files']
}
}
});
Upvotes: 0
Reputation: 85
You can get the data using the props:
<div id="files" :files="{{ $files }}"></div>
And in your Vue
instance:
new Vue({
el: "#files",
props: ['files'],
data: {
list: []
},
ready: {
this.list = JSON.parse(this.files)
}
});
The props option files
is filled by the $files
from laravel
, and is parsed to json
to use in vue
, after the ready option, you can use in HTML
:
<div v-for="l in list">
@{{ l.name }}
@{{ l.last_name }}
</div>
The list contains the json
with the files that comes from Laravel
controller.
Upvotes: 2