Best practice to pass data from Laravel to Vue component

孤街浪徒 提交于 2020-12-01 09:26:49

问题


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?


回答1:


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.




回答2:


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.




回答3:


This was the only way that works for me:

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

JSON parsed solutions prints data in HTML.



来源:https://stackoverflow.com/questions/51366437/best-practice-to-pass-data-from-laravel-to-vue-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!