Whenever I send a 'POST' or 'DELETE' request, the data doesn't update automatically. I have to manually reload the page to see the updated information. Is there an easy way to refresh the data after making any 'POST' / 'DELETE' / 'PUT' request?
What steps should I follow to implement this functionality?
I'm new to working with Vue.js.
Here is the code snippet:
template
// Display list of articles
<b-row>
<div v-for="article in articles" v-bind:key="article.id">
<b-card v-bind:title="article.title" img-src="https://picsum.photos/600/300/?image=25" img-alt="Image" img-top tag="article" style="max-width: 20rem;" class="text-left mb-2 mt-4 ml-2">
<b-card-text>
{{ article.content }}
</b-card-text>
<b-button v-bind:href="'/'+ article.id" variant="primary">See more...</b-button>
<button class="btn btn-danger btn-sm ml-1" v-on:click="deleteArticle(article)">
Delete
</button>
</b-card>
</div>
</b-row>
// Create new article form
<div class="mt-5">
<h2 class="text-left mb-3"> Create new article </h2>
<b-form @submit.prevent="create" method="post">
<b-form-group>
<b-col sm="1">
<label :for="`type-text`">Title:</label>
</b-col>
<b-col sm="9">
<b-form-input :id="`type-text`" :type="text" v-model="article.title" required></b-form-input>
</b-col>
</b-form-group>
<b-form-group>
<b-col sm="1">
<label for="textarea-no-auto-shrink">Content:</label>
</b-col>
<b-col sm="9">
<b-form-textarea id="textarea-no-auto-shrink" placeholder="Write something..." v-model="article.content" required rows="3" max-rows="3"></b-form-textarea>
</b-col>
</b-form-group>
<b-form-group>
<b-col sm="1">
</b-col>
<b-button type="submit" class="mt-2 ml-3">Submit</b-button>
</b-form-group>
</b-form>
</div>
script
import axios from 'axios'
export default {
name: 'List',
props: {},
data() {
return {
articles: [],
article: {
title: '',
content: '',
}
}
},
mounted() {
axios
.get('http://127.0.0.1:8000/api/')
.then(response => (this.articles = response.data))
.catch(error => console.log(error))
},
methods: {
create() {
axios
.post('http://127.0.0.1:8000/api/',
this.article
)
.then(response => {
response.data.article = null;
})
.catch(error => console.log(error))
},
deleteArticle(artcl) {
if (confirm('Delete ' + artcl.title)) {
axios.delete(`http://127.0.0.1:8000/api/${artcl.id}`)
.then(response => {
this.all();
return response;
});
}
}
},
}