解决a-form/a-form-model重置表单使用resetFields()函数重置无效问题

在点击表单重置按钮之后,发现页面字段值没有进行置空?下面是我在平时遇到的一些相关问题以及解决方案。
问题提出
在这里插入图片描述

在点击了多次重置按钮以后,发现表单对象中user字段值始终都是‘ss’,相关代码如下:

<template>
<div>
  <a-form-model
    ref="ruleForm"
    layout="inline"
    :model="formInline"
    @submit="handleSubmit"
    @submit.native.prevent
  >
    <a-form-model-item  prop="user" label="user">
      <a-input v-model="formInline.user" placeholder="Username">
        <a-icon slot="prefix" type="user" style="color: rgba(0, 0, 0, 0.25)" />
      </a-input>
    </a-form-model-item>
    <a-form-model-item  prop="password" label="password">
      <a-input
        v-model="formInline.password"
        type="password"
        placeholder="Password"
       
      >
        <a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
      </a-input>
    </a-form-model-item>
    <a-form-model-item>
      <a-button
        type="primary"
        html-type="submit"
        :disabled="formInline.user === '' || formInline.password === ''"
      >
        Log in
      </a-button>
      <a-button type="primary" @click="resetForm"> rest </a-button>
    </a-form-model-item>
  </a-form-model>
</div>
  
</template>
<script>
import MyFormModel from './MyFormModel.vue'
export default {
  name: "MyRestFieldsTest",
  components:{
    MyFormModel
  },
  data() {
    return {
      formInline: {
        user: "",
        password: "",
      },
    };
  },
  created() {
    this.formInline.user='ss'
    // console.log("father-mounted");
  },
  methods: {
    handleSubmit(e) {
      console.log(this.formInline);
    },
    resetForm() {
      console.log("11111111,重置了",this.formInline);
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style>
</style>

问题分析
在代码中重置按钮事件使用了,resetFields()这一个API函数,随后去ant-design-vue管网看了一下,发现它对应解释是这样的。
在这里插入图片描述
划重点,重置为初始值,顾名思义,为最原始的值。在vue中设置原始值地方好像不止一个。一个就是在data()属性里面,再一个就是一些钩子函数也可以。问题找到了,代码中,在created()钩子函数对表单项user进行了一次赋值。

created() {
    this.formInline.user='ss'
    // console.log("father-mounted");
  },

解决方案:
分两种情况:
第一个,如果是这个初始赋值无关紧要,可有可无,删除即可重置成功。
第二个,如果这个初始赋值必须存在,可以考虑在另一个钩子函数赋值。因为我猜测API文档中写的初始值是在渲染之前的相关的赋值,至于渲染成功之后赋值应该就不算初始值了。当然为了证实,我进行了实验。
vue中在渲染前后相关的钩子函数有这几个,分别是:beforeCreate()created()beforeMount()mounted()。而且顺序也是依次执行的,所以created()以及beforeCreate()都不予考虑。

  • beforeMount()钩子函数
beforeMount() {
  this.formInline.user='ss'
},

对应的结果是:
在这里插入图片描述

结果和created()钩子函数都是一样的,没有重置成功。

  • mounted()钩子函数
mounted() {
  this.formInline.user='ss'
},

对应的结果是:
在这里插入图片描述

重置成功。

综上,在mounted()钩子函数是可以进行重置成功的。所以,在需要进行赋值时,解决a-form/a-form-model重置表单使用resetFields()函数重置无效问题的方案就是,在mounted()钩子函数中进行赋值操作。
最后,关于vue生命周期钩子的执行顺序可以点此,这是我对其进行的一些整理。当然,可以去官方的对其vue生命周期钩子的一些解释。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值