vue3+elemeng-plus表单校验及resetFields使用

vue3+element-plus表单验证与登录

<template>
    <div>
        <el-form
            label-width="100px"
            ref="formlabelref"
            :rules="rules"
            :model="formlabel"
            style="width: 60%;margin:0 auto"
            class="demo-ruleForm"
        >
            <el-form-item label="Name" prop="name">
                <el-input v-model="formlabel.name"></el-input>
            </el-form-item>
            <el-form-item label="Password"  prop="password">
                <el-input v-model="formlabel.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">Query</el-button>
                <el-button @click="reset">Reset</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang='ts'>
import { defineComponent, ref, unref } from 'vue'
import { userlogin } from '../utils/api'
import {throttle} from '../utils/util'
import {
    ElMessage
} from 'element-plus';

export default defineComponent({
    name: 'login',
    setup() {
        let formlabelref = ref()
        let formlabel = ref({
            name: '',
            password: '',
        })
        let rules= ref({
            name: [
            {
                required: true,
                message: 'Please input name',
                trigger: 'blur',
            }
            ],
            password: [
            {
                required: true,
                message: 'Please input password',
                trigger: 'blur',
            },
            ],
        }) 
        const submittemp = () => {
            const form = unref(formlabelref)
            form.validate((valid)=>{
                if(!valid){
                    return ElMessage.error('用户名或密码未输入')
                }else{
                    userlogin(form.model).then(res => {
                        if (res.code === 200) {
                            ElMessage.success(res.msg);
                        } else {
                            ElMessage.error(res.msg);
                        }
                    })
                }
                
            })
        }
        const submit = throttle(submittemp,3000)
        const reset =  () => {
            const form = unref(formlabelref)
            form.resetFields()
        }
        return {
            rules,
            formlabel,
            formlabelref,
            submit,
            reset
        }
    }
})
</script>

<style lang='less'>
</style>

你可能感兴趣的:(vue3,bug处理,vue.js,javascript,前端)