Reputation: 734
I've been working on lots of forms on my Nuxt app, and sometimes after Axios call setting the data manually to override entered values seems to be a bad idea especially for big objects.
...
data(){
return {
name : '',
}
}
...
$axios.post('/users/create', name).then( resp =>{
this.name = '' // changing it back to the initial value.
})
It's fine with a small object, but when it gets big it seems to be a task. Not sure if my curiosity is clear, but all I want to do is to make the data back to the initial value without refreshing the page.
Upvotes: 0
Views: 846
Reputation: 102
Assuming that you have a huge form or you don't want to clear one by one field
// Declaring the default form values
const defaultOtherForm = {
name: null,
age: 18,
}
...
data: () => ({
form: {
name: null,
age: null
},
otherForm: Object.assign({}, defaultOtherForm)
})
// After ajax called. You can use "loop" to clear values dynamically
Object.keys(this.form).forEach((key) => this.form[key] = null)
// Another way. Declare initialized form values and override with initialized values after ajax called successful
this.otherForm = defaultOtherForm
But if you want to use "native reset" form. You can wrap by a form
// After ajax called. Just call reset() method via ref
this.$refs.userForm.reset()
Upvotes: 0
Reputation: 6912
You can put your data object
in a variable
and reset it using loop, once the Axios
request get finished
const initialObject = {
name : 'foo'.
...
}
...
data(){
return {
...initialObject
}
}
...
$axios.post('/users/create', name).then( resp => {
for (let key in this.$data) {
this[key] = initialObject[key]
}
})
Upvotes: 1