一、实现表单输入校验

  • el-form标签上定义rules属性进行双向绑定  :rules="loginRules"  ,loginRules这个校验规则定义在data数据里,(1)要注意的是loginRules里面定义username和password需要与表单数据绑定的参数同名。(2)username: [{ required: true, message: '账号不能为空哦', trigger: 'blur' }] , 其中required校验必填不必填,message是提示信息,trigger:'blur'是失去焦点后就去校验数据
  • el-form-item  定义    prop="username" , 每一个el-form-item表单项上需要表明跟哪个参数去校验

 

 

 

二、 表单预校验

  • 在el-form表单标签上添加代码 ref="loginRef"
  • methods里面,点击登录调用的方法clickLogin()里面,先获取登录的表单对象 this.$refs['loginRef']  ,然后把表单校验的结果传给validate里面的回调函数res。
    clickLogin() {
          //获取登录的表单对象
          this.$refs['loginRef'].validate((res) => {
            if (res) {
              // 调用后端登录的结果
              this.loginRequest()
            }
          })
        },

 

<script>
import LoginBack from '../components/LoginBack.vue'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      // 登录表单数据
      loginForm: {
        username: '',
        password: '',
        status: false,
      },
      // 登录数据的校验规则
      loginRules: {
        username: [{ required: true, message: '账号不能为空哦', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空哦', trigger: 'blur' }],
      },
    }
  },
  methods: {
    clickLogin() {
      //获取登录的表单对象
      this.$refs['loginRef'].validate((res) => {
        if (res) {
          // 调用后端登录的结果
          this.loginRequest()
        }
      })
    },

    async loginRequest() {
      // 调用登录接口 发送请求进行登录
      const response = await this.$api.loginApi(this.loginForm)
      if (response.status === 200) {
        this.$router.push({ name: 'allProject' })
        ElMessage({
          message: '登录成功',
          type: 'success',
        })
      } else {
        ElMessage({
          message: response.data,
          type: 'warning',
        })
      }
    },
  },
  components: {
    LoginBack,
  },
}
</script>

<style scoped>
.login_box {
  width: 500px;
  height: 400px;
  margin: calc((100vh - 400px) / 2) auto;
}

.title {
  padding-bottom: 5px;
  text-align: center;
}
</style>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐