resetFields失效与$nextTick

发布时间 2023-05-30 17:53:46作者: 风中的摇坠

 这个问题会比较常见。

我们经常会遇见这么写:update和add共用一个弹窗。update时,表单回显;add时,需要清空表单。

 

 

我们可能会用到Element-Ui表单的resetFields()方法,但是如果操作不当,这个resetFields()方法并不会生效。

官网对这个方法的定义:

resetFields: 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果

重置为初始值,这个初始值指的是mount()方法前的初始值,所以我们在对form表单进行赋值时,需要在mount()方法之后。

 

先看一个对失效且对nextTick乱使用的例子:

// update回显方法
updateInit(id) {
  get(id).then(res => {
    this.$nextTick(() => {
      this.form.id = id;
      this.form.appId = res.data.appId;
      this.form.productId = res.data.productId;
      this.form.productName = res.data.productName;
      this.form.productPrice = res.data.productPrice;
      this.form.productPrice = res.data.productPrice;
      this.form.currencyCode = res.data.currencyCode;
      this.form.enableStatus = res.data.enableStatus;
      // 弹框显示
      this.dialogFormVisible = true;
    });
  });
}

这个例子最失败的问题在于,在nextTick中调用了触发界面渲染的方法,当首次点击的是更新按钮而不是新增按钮,导致mount()方法之前对form进行了赋值。所以后面点击新增按钮调用resetFields时,仍然显示之前update回显的form数据。

 

正确写法:

// update回显方法
updateInit(id) {
    get(id).then(res => {
         // 弹框显示
        this.dialogFormVisible = true;
        this.$nextTick(() => {
            this.form.id = id;
            this.form.appId = res.data.appId;
            this.form.productId = res.data.productId;
            this.form.productName = res.data.productName;
            this.form.productPrice = res.data.productPrice;
            this.form.productPrice = res.data.productPrice;
            this.form.currencyCode = res.data.currencyCode;
            this.form.enableStatus = res.data.enableStatus;
        });
    });
}

这里也揭示了$nextTick的绝大多数使用模板:

// 这里进行首次渲染的操作
this.$nextTick(() => {
  // 这里面进行数据操作            
});