【问题标题】:Vue data back to default value after an Ajax callAjax 调用后 Vue 数据恢复为默认值
【发布时间】:2020-11-17 11:52:09
【问题描述】:

我一直在我的 Nuxt 应用程序上处理大量表单,有时在 Axios 调用之后手动设置数据以覆盖输入的值似乎是一个坏主意,尤其是对于大对象。


...
data(){

  return { 
   name : '',
  }

}
...

$axios.post('/users/create', name).then( resp =>{ 


   this.name = '' // changing it back to the initial value.


})

小物件没问题,但当它变大时,它似乎是一项任务。不知道我的好奇心是否清楚,但我想做的就是在不刷新页面的情况下让数据恢复到初始值。

【问题讨论】:

  • 在组件挂载时存储对象初始状态的临时值,然后循环该对象并相应地设置每个相应的值

标签: vue.js vue-component nuxt.js


【解决方案1】:

假设你有一个巨大的表格或者你不想一个一个地清除字段

// 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()

【讨论】:

    【解决方案2】:

    一旦Axios 请求完成,您可以将data object 放入variable 并使用循环重置它

    const initialObject = {
     name : 'foo'.
     ...
    }
    ...
    data(){
    
      return {
        ...initialObject
      }
    
    }
    ...
    
    $axios.post('/users/create', name).then( resp => { 
       for (let key in this.$data) {
         this[key] = initialObject[key]
       }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-10
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多