我一直在我的Nuxt应用程序上处理很多表单,有时在Axios调用之后,手动设置数据覆盖输入的值似乎是一个坏主意,特别是对于大对象。
...
data(){
  return { 
   name : '',
  }
}
...
$axios.post('/users/create', name).then( resp =>{ 
   this.name = '' // changing it back to the initial value.
})它对于一个小的物体是很好的,但是当它变大的时候,它似乎是一项任务。不知道我的好奇心是否明确,但我想做的就是让数据返回到初始值,而不刷新页面。
发布于 2020-07-28 14:01:31
您可以将data object放在variable中,并在Axios请求完成后使用循环重置它
const initialObject = {
 name : 'foo'.
 ...
}
...
data(){
  return {
    ...initialObject
  }
}
...
$axios.post('/users/create', name).then( resp => { 
   for (let key in this.$data) {
     this[key] = initialObject[key]
   }
})发布于 2020-07-28 14:12:06
假设您有一个很大的表单,或者您不想逐个清除字段
// 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但是如果你想使用“本地重置”的形式。您可以通过表单包装
// After ajax called. Just call reset() method via ref
this.$refs.userForm.reset()https://stackoverflow.com/questions/63127357
复制相似问题