Skip to content

js的form表单重置写法

参考:https://blog.csdn.net/jefferylong/article/details/120744554

ts写法:https://element-plus.org/zh-CN/component/form.html#自定义校验规则

html
<template>
    <div>
        <div class="main">
            <!-- el-form中的ref属性不能少,可以任意起个名字 -->
            <!-- model的值和reactive中的对象相对应 -->
            <el-form ref="userinfoRef" :model="state.account">
                <!-- el-form-item中的prop属性不能少,且值必须是reactive中的具体的字段名字 -->
                <el-form-item label="姓名" prop="username">
                    <el-input
                        v-model="state.account.username"
                        placeholder="请输入姓名"
                    ></el-input>
                </el-form-item>
                <el-button type="warning" @click="resetForm">重置</el-button>
                <el-button type="warning" @click="doSubmit">提交</el-button>
            </el-form>
        </div>
    </div>
</template>
<script setup>
import {getCurrentInstance, reactive} from 'vue'
const {proxy} = getCurrentInstance()
const state = reactive({
    account: {  // form表单中的值,可能会有多个,所以定义成对象最省事儿
        username: ""
    }
})
const resetForm = ()=>{
    // vue3中js的写法,从当前proxy对象中的$refs找到userinfoRef,然后执行其resetFields方法即可重置
    // 你可以认为是固定写法
    // 如果是ts的写法,就参考element-plus官网
    proxy.$refs.userinfoRef.resetFields()
}
const doSubmit = ()=>{
    console.log(state.account)
}
</script>