使用Vue和axios無需刷新頁面更新數據
P粉614840363
P粉614840363 2023-08-25 19:15:28
0
1
492
<p>我有一個在 Vue 和 Axios 上製作的包含 2 個選項卡(問題和數據)的頁面。 在第一個選項卡中,我填寫表單並提交 - 儲存按鈕 <strong>v-on:click="save"</strong>。 </p> <pre class="brush:php;toolbar:false;">save: function() { axios({ method: 'patch', url: url, data: this.data }) .then(function (response) { this.data = response.data; }</pre> <p>在第二個選項卡(資料)中,我有已儲存資料的清單:</p> <pre class="brush:php;toolbar:false;">mounted() { axios .get('/api/recommended-products/?patient_uuid=' '{{patient.uuid}}') .then(response => (this.data= response.data.results)) }</pre> <p>現在,當我更改「問題」標籤中的答案時,「資料」標籤中的清單應該會自動變更。如果我刷新頁面,它就會改變 - Mounted() 有效。 我嘗試創建 <strong>updateList()</strong> 函數:</p> <pre class="brush:php;toolbar:false;">updateList: function() { axios .get('/api/recommended-products/?patient_uuid=' '{{patient.uuid}}') .then(response => (this.data= response.data.results)) }</pre> <p>並將其加到 <strong>save()</strong> 函數中,例如:</p> <pre class="brush:php;toolbar:false;">save: function() { axios({ method: 'patch', url: url, data: this.data }) .then(function (response) { this.data = response.data; this.updateList(); }</pre> <p>問題是這種方式第二次可以工作(有時有效有時不行)。所以我只是將 <strong>location.reload();</strong> 加入 <strong>save()</strong> 但我不喜歡這個方法。是否可以在不刷新頁面的情況下更新資料列表?我對 <strong>updateList()</strong> 函數做錯了什麼? </p>
P粉614840363
P粉614840363

全部回覆(1)
P粉949267121

在我看來,你應該使用 vuex 及其 getter。

這樣,您在所有應用程式中就只有一個請求,一旦狀態更新,資料就會自動刷新。

然後,您可以使用計算屬性存取數據,該屬性將在狀態更新時自動重新渲染。


以下是使用多個選項卡的範例: https://codesandbox.io/s/vuex-axios-demo-forked-m0cqe4?file=/src/App.vue

在此範例中,我透過 JsonPlaceHolder API 載入貼文資訊。

每次重新傳送表單(使用函數)。呼叫 store 的操作,然後更新狀態,從而觸發 getter 重新渲染資料。

注意:我將第一篇文章載入到 Mounted 中,預設值為 1。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!