我有一個使用 Laravel 和 Vue 的應用程式。控制器有一個類似于這個索引的方法
public function index(Request $request)
{
$people = Person::all();
if ($request->ajax()){
return response()->json($people);
}
return view('people.index')->withPeople($people);
}
問題是:在前端(Vue)獲取資料的正確方法是什么?
我們可以使用類似于此代碼
<example-component@prop('people', $people)></example-component>
在組件中傳遞變數或者我們可以使用 Axios。
uj5u.com熱心網友回復:
我可以做類似以下的事情
$people = Person::all();
if ($request->ajax()){
return response()->json($people);
}
使用 Axios
getAll() {
return axios.get(`${base_url}/persons`);
}
獲取所有人員
getPersons() {
return persons
.getAll()
.then(response => {
// console.log(this.persons);
this.persons = response.data;
})
.catch(error => {
console.log(error);
})
.finally(() => (this.loading = false));
},
在組件中
<example-component>{{persons}}</example-component>
uj5u.com熱心網友回復:
您可以在腳本標簽內回顯 php 變數
在 *.blade.php
<script>
var people = {{ $people }};
</script>
在 vue 腳本中
const people = people; // or const people = window.people || ''
new Vue {
data() {
return { people }
}
}
在 vue 模板中
<example-component@prop('people', people)></example-component>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/342606.html
上一篇:如何在單擊時執行多個事件?
