Home  >  Q&A  >  body text

Use Vue and axios to update data without refreshing the page

<p>I have a page with 2 tabs (Questions and Data) made on Vue and Axios. In the first tab I fill out the form and submit - save button <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>In the second tab (Data) I have a list of saved data: </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>Now when I change the answer in the Questions tab, the list in the Data tab should change automatically. If I refresh the page it changes - Mounted() works. I tried creating the <strong>updateList()</strong> function: </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>and add it to the <strong>save()</strong> function, for example: </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>The problem is that this way works the second time (sometimes it works and sometimes it doesn't). So I just added <strong>location.reload();</strong> to <strong>save()</strong> but I don't like this approach. Is it possible to update the data list without refreshing the page? What am I doing wrong with the <strong>updateList()</strong> function? </p>
P粉614840363P粉614840363397 days ago501

reply all(1)I'll reply

  • P粉949267121

    P粉9492671212023-08-26 11:52:00

    In my opinion, you should use vuex and its getter.

    This way you have only one request across all your applications and the data is automatically refreshed once the status is updated.

    You can then access the data using a computed property, which will automatically re-render when the state updates.


    The following is an example of using multiple tabs: https://codesandbox.io/s/vuex-axios-demo-forked-m0cqe4?file=/src/App.vue

    In this example, I load the post information through the JsonPlaceHolder API.

    Resend the form each time (using function). Call the store operation and then update the state, thus triggering the getter to re-render the data.

    Note: I loaded the first post into Mounted with a default value of 1.

    reply
    0
  • Cancelreply