[Vuejs]-Porperly way to share data between Laravel and Vue

0๐Ÿ‘

I could do something like the following

$people = Person::all();
    if ($request->ajax()){
        return response()->json($people);
    }

Using Axios

getAll() {      

    return axios.get(`${base_url}/persons`);

}

Get all the persons

getPersons() {
  return persons
    .getAll()
    .then(response => {
   
      // console.log(this.persons);
  
      this.persons = response.data;
     
    })
    .catch(error => {
      console.log(error);          
    })
    .finally(() => (this.loading = false));
},

In component

<example-component>{{persons}}</example-component>

0๐Ÿ‘

You can echo php variable inside script tag

In *.blade.php

<script>
var people = {{ $people }};
</script>

In vue script

const people = people; // or const people = window.people || ''
new Vue {
  data() {
    return { people }
  }
}

In vue template

<example-component@prop('people', people)></example-component>

Leave a comment