将数据从 Laravel 传递到 Vue 组件的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51366437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best practice to pass data from Laravel to Vue component
提问by Dill
This is my blade code
这是我的刀片代码
<div id="app">
<Testcomponent bam-wam="ham" />
</div>
This is my VueJS Component code
这是我的 VueJS 组件代码
<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 appor simply Pass data throw props like I did in this code?
这段代码运行良好,但我问的是使用 Axios 和 Vuex 从我的 Laravel 应用程序中获取数据还是像我在这段代码中所做的那样简单地传递数据抛出道具更好?
回答by Summonjoy
Pass data through propsis the best way.
通过 props 传递数据是最好的方式。
<my-component my-data="yourData"></my-component>
If you want to use laravelvariable for data from blade then,
如果你想对来自刀片的数据使用laravel变量,那么,
<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.
尽量避免api调用。它将减少对服务器的请求总数并暴露更少数量的 api 端点。
回答by Hasan Wajahat
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:
如果数据可用于添加组件的视图。那么将 php 数组从 laravel 传递到 vue 组件的最佳方法是使用 json 编码,如下所示:
<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
.
这将使您可以轻松地对 Vue 控制器中的 php 数组执行操作,就好像它是一个 JS 对象一样。请记住,您必须对@json
.
For simple strings you can just directly pass it as props without the encoding.
对于简单的字符串,您可以直接将其作为 props 传递而无需编码。
This approach is better than creating a new API specifically for this component.
这种方法比专门为这个组件创建一个新的 API 更好。