element-plus 表单验证demo

<template>
  <div class="container my-4 mx-auto p-4">
    <el-radio-group v-model="labelPosition" label="label position">
      <el-radio-button label="left">Left</el-radio-button>
      <el-radio-button label="right">Right</el-radio-button>
      <el-radio-button label="top">Top</el-radio-button>
    </el-radio-group>
    <div style="margin: 20px" />
    <el-form ref="form" :label-position="'right'" label-width="100px" :model="formInLine" style="max-width: 460px" :rules="rules">
      <el-form-item label="账号" prop="user">
        <el-input v-model="formInLine.user" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formInLine.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="onSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import type { FormInstance } from 'element-plus';
import { ElMessage as message, ElMessageBox as messageBox } from 'element-plus';
export default {
  data() {
    return {
      labelPosition: 'left',
      formInLine: {
        user: '',
        password: '',
      },
      rules: {
        user: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度为 3 to 5', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 200, message: '长度为 6 to 200', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    async onSubmit() {
      (this.$refs.form as FormInstance)?.validate((flag: boolean) => {
        if (flag) {
          localStorage.setItem('token', '1');
          this.$router.push('/index');
        } else {
          message.warning('表单提交有错误');
          // messageBox.alert('This is a message', 'Title', {
          //   confirmButtonText: 'OK',
          //   callback: (action: any) => {
          //     console.log(action);
          //   },
          // });
          console.log(messageBox);
        }
      });
    },
  },
};
</script>

<style scoped lang="scss"></style>

posted @ 2023-09-25 15:57  bronana  阅读(108)  评论(0编辑  收藏  举报