Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question

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.

share|improve this answer

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']
        }
    }  
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.