[英]How do I pass data from PHP Laravel to Vue.js and re-render a Vue.js component when the data changes?
我對Vue.js還是有點陌生,所以我可能會從根本上對它的反應性有所誤解,但是基本上,我想將一些數據從PHP Laravel傳遞到Vue.js組件並擁有Vue.js組件數據更改時自動更新。
我在SO上看到過幾篇類似的文章,建議我使用props
將數據從Laravel Blade模板傳遞到Vue.js組件。 這是一個例子:
如何在Laravel Blade中將PHP變量傳遞給Vue組件實例?
我的工作非常正常,但是現在我只能在頁面加載后數據動態更改時如何使組件更新。
具體來說,我在特定網頁上有一個報表表,當用戶單擊某些按鈕等時,我使用Ajax調用Laravel控制器操作,該操作在我的Laravel模型中重新運行查詢以獲取新的數據。報告。
我將數據存儲在PHP數組/ JSON中,並且該數據已正確返回給客戶端,並且可以在JS中訪問它,但是現在,我需要執行什么操作才能在Vue中強制使用報表組件。 js基本上根據我剛收到的數據重新渲染? 有沒有一種方法可以“更新道具”,以便Vue.js能夠檢測到更改並自動為我重新呈現整個報表組件?
這是我遇到的問題,經過大量研究后,我找不到如何執行此操作的地方。 謝謝。
您是否在Vue組件之外使用Ajax? 或作為一種方法?
我有一個示例,說明如何從組件本身內部動態更新Vue數據。 我不確定如何讓外部JS直接更新Vue組件,但我認為這是一個不錯的選擇。 我使用的是axios
而不是Ajax,但是原理是相同的(大多數5.5版本以后的Laravel安裝默認都包含Axios)。
<template>
<div>
<div id="reports">
<!-- Display data -->
{{ reports }}
</div>
<button @click="refreshReports">Refresh</button>
</div>
</template>
<script>
export default {
data() {
return {
endpoint: '/api/MY_ROUTE/'
};
},
props: {
reports: Object
},
methods: {
// Make Axios call to API endpoint
refreshReports() {
// GET version
axios.get(this.endpoint)
.then(({data}) => {
this.reports = data.data;
});
// POST version
axios.post(this.endpoint, {
KEY: 'VALUE',
}).then(({data}) => {
this.reports = data.data;
});
/*
`data.data` assumes the returned response is a JSON Resource
if it's not returning the correct data, put a `console.log(data)` and see how it's getting returned!
*/
}
}
};
</script>
在routes/api.php
文件中的哪里有這樣的路由:
// GET version
Route::get('MY_ROUTE', 'ReportController@getReports');
// POST version
Route::post('MY_ROUTE', 'ReportController@getReports');
您的控制器將具有以下方法:
// app/Http/Controllers/ReportController
public function getReports(Request $request) {
return Reports::all();
}
那有意義嗎?
更新:
我不確定如何讓外部JS直接更新Vue組件
我知道您可以導入外部JS腳本並在方法中使用它們的功能,但是我從來沒有那樣做過。
就像是:
<script>
import { myFunction } from '../external.js'
export default {
methods: {
refreshReports() {
// I have no idea if this is the correct way to do it, just a guess!
this.reports = myFunction();
}
}
};
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.