Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to pass data from Laravel to Vue component

This is my blade code

<div id="app">
  <Testcomponent bam-wam="ham" />
</div>

This is my VueJS Component code

<script>
    export default {
        name: "ExampleComponent",
        props: [
            'bamWam'
        ],
        data () {
            return {

            };
        },
        created() {
            console.log(this.bamWam);
        }
    }
</script>

Question is

This code runs good but I am asking what is better using Axios and Vuex to fetch data from my Laravel app or simply Pass data throw props like I did in this code?

like image 873
Dill Avatar asked Jul 16 '18 16:07

Dill


People also ask

How do I pass data from Laravel blade to Vue component?

Simply you can take this in your blade: <span hashid="{{ Auth::user()->id }}"></span> and in your vue component do like: <script> export default { data: function () { return { hashid: '' } } } </script> and console it anywhere, it'll give you auth id!

Is Vue good with Laravel?

Laravel supports Model–View–Controller (MVC) design pattern, which is ideal for developing user interfaces. Laravel has object-oriented syntax and many libraries supporting the use of objects. Vue and Laravel work perfectly together.


Video Answer


3 Answers

Pass data through props is the best way.

<my-component my-data="yourData"></my-component>

If you want to use laravel variable for data from blade then,

<my-component my-data="'{{ $data->id }}'"></my-component>

<my-component :my-data="'{!! json_encode($data) !!}'"></my-component>

Avoid api call as much as possible. It will reduce the total number of request to server and expose fewer number of api endpoint.

like image 66
Summonjoy Avatar answered Oct 10 '22 16:10

Summonjoy


If the data is available to the view where the component is added. Then the best way to pass php arrays from laravel to a vue component is to utilize json encoding like so:

<my-component :needed-data='@json($laravelCollection)'></my-component>

This will make you will be easily to perform actions to the php array in the Vue controller as if it was a JS object. Keep in mind that you have to use single quotes for @json.

For simple strings you can just directly pass it as props without the encoding.

This approach is better than creating a new API specifically for this component.

like image 7
Hasan Wajahat Avatar answered Oct 10 '22 16:10

Hasan Wajahat


This was the only way that works for me:

<my-component :data="{{ $collection }}"></my-component>

JSON parsed solutions prints data in HTML.

like image 3
NReyes Avatar answered Oct 10 '22 16:10

NReyes