尝试用Vue3+Typescript+ElementPlus写一个简单的表单验证,代码如下

 LoginView.vue文件

<template>
  <!-- :model是数据对象,:rules是校验规则 -->
  <el-form :model="userInfo" :rules="infoRules" class="form">
    <!-- prop是userInfo里面的属性名 -->
    <el-form-item label="账号" prop="phone">
      <!-- v-model进行数据双向绑定 -->
      <el-input type="text" v-model="userInfo.phone"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="text" v-model="userInfo.password"></el-input>
    </el-form-item>
  </el-form>
  <el-button type="primary">登录</el-button>
</template>

<script lang="ts">
import { Options, mixins } from "vue-class-component";
import { LoginModel } from "@/viewmodel/LoginModel";

@Options({})
//校验的规则都写在了LoginModel.ts文件中,直接继承类就可以使用
export default class LoginView extends mixins(LoginModel) {}
</script>

<style scoped>
.form {
  width: 300px;
  height: 100px;
  margin: 0 auto;
}
</style>

 LoginModel.ts文件

import { Vue } from "vue-class-component";

export class LoginModel extends Vue {
  userInfo = {
    phone: "",
    password: "",
  };

  infoRules = {
    phone: [
      { required: true, message: "账号不能为空", trigger: "blur" },
      { min: 5, max: 11, message: "请输入正确的账号", trigger: "blur" },
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" },
      { min: 5, max: 11, message: "请输入正确的密码", trigger: "blur" },
    ],
  };
}

 运行以后发现没有错误信息显示

 

 检查一下代码发现是trigger参数错了,加上双引号即可

 

 再运行一下就成功了

 

 

 

Logo

前往低代码交流专区

更多推荐