Vue Form表单的使用方法(rules格式校验网络校验键盘按键监听)

 更新时间:2024年11月22日 09:42:00   作者:张雨zy  
本文介绍了在Vue.js中使用表单校验规则(rules)进行网络请求校验的方法,以及如何通过formRef引用表单对象并进行键盘按键监听,感兴趣的朋友跟随小编一起看看吧

Form表单

rules格式校验

可以在validator中进行网络请求,实现网络校验

const formRules = {
  userName: [{required: true, message: "用户名不能为空", trigger: 'blur'}, {
    min: 5,
    max: 10,
    message: "长度必须5-10位",
    trigger: 'blur'
  }],
  passWord: [{required: true, message: "密码不能为空", trigger: 'blur'}],
  reference: [{
    validator: referenceValidity,
    required: true,
    trigger: "blur",
  },],
}
function referenceValidity(rule, value, callback) {
  console.log('校验推荐人')
  if (value === "" || value === undefined) {
    callback(new Error("请输入推荐人姓名"));
  } else {
    //请求网络校验推广人
    // console.log("输入的推荐人姓名:" + value)
    // const _url = "xxxxxxxxxxx";
    // let param = {};
    // param.promotionPecialistName = value;
    // get(this.$http, _url, param).then(function (response) {
    //   let res = response.data;
    //   if (res.code === "I000000") {
    //     if (res.data.isFlag) {
    //       callback()
    //     } else {
    //       callback(new Error("推荐人不存在"))
    //     }
    //   } else {
    //     callback(new Error("推荐人不存在"))
    //   }
    // });
    callback(new Error("推荐人不存在"))
  }
}

formRef引用form对象 form表单中关联formRef(引用对象),form(表单内容),formRules(校验规则)

<el-form ref="formRef" :model="form" :rules="formRules">
const formRef = ref()
function reqLogin() {
  console.log("账号信息", form.value)
  formRef.value.validate((valid) => {
    console.log("formRef valid = ", valid)
    if (valid) {
      setToken()
      store.commit("setUserInfo", form.value)
      showToast("登录成功")
      router.push('/')
    }
  })
}

键盘监听

onMounted(() => {
  console.log("页面加载")
  document.addEventListener('keyup', onkeyup)
})
onBeforeUnmount(() => {
  document.removeEventListener('keyup', onkeyup)
})
function onkeyup(e) {
  if (e.key === 'Enter') {
    reqLogin()
  }
}

完整代码

<script setup>
import {onBeforeUnmount, onMounted, ref} from "vue";
import {Lock, User} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import {setToken} from "../utils/CookieUtil.js";
import {showToast} from "../utils/ToastUtil.js";
import {useStore} from "vuex";
const router = useRouter()
const store = useStore()
const form = ref({
  userName: "",
  passWord: "",
  reference: ""
})
const formRef = ref()
const formRules = {
  userName: [{required: true, message: "用户名不能为空", trigger: 'blur'}, {
    min: 5,
    max: 10,
    message: "长度必须5-10位",
    trigger: 'blur'
  }],
  passWord: [{required: true, message: "密码不能为空", trigger: 'blur'}],
  reference: [{
    validator: referenceValidity,
    required: true,
    trigger: "blur",
  },],
}
function referenceValidity(rule, value, callback) {
  console.log('校验推荐人')
  if (value === "" || value === undefined) {
    callback(new Error("请输入推荐人姓名"));
  } else {
    //请求网络校验推广人
    // console.log("输入的推荐人姓名:" + value)
    // const _url = "xxxxxxxxxxx";
    // let param = {};
    // param.promotionPecialistName = value;
    // get(this.$http, _url, param).then(function (response) {
    //   let res = response.data;
    //   if (res.code === "I000000") {
    //     if (res.data.isFlag) {
    //       callback()
    //     } else {
    //       callback(new Error("推荐人不存在"))
    //     }
    //   } else {
    //     callback(new Error("推荐人不存在"))
    //   }
    // });
    callback(new Error("推荐人不存在"))
  }
}
function onkeyup(e) {
  if (e.key === 'Enter') {
    reqLogin()
  }
}
onMounted(() => {
  console.log("页面加载")
  document.addEventListener('keyup', onkeyup)
})
onBeforeUnmount(() => {
  document.removeEventListener('keyup', onkeyup)
})
function reqLogin() {
  console.log("账号信息", form.value)
  formRef.value.validate((valid) => {
    console.log("formRef valid = ", valid)
    if (valid) {
      setToken()
      store.commit("setUserInfo", form.value)
      showToast("登录成功")
      router.push('/')
    }
  })
}
</script>
<template>
  <div style="height: 100vh;width: 100vw;display: flex;flex-direction: row">
    <div class="flex-col-center" style="width: 70%;height: 100%;background: #213547;">
      <span style="font-size: 40px;color: white;">测试系统登录页面</span>
      <span style="font-size: 20px;color: white;">演示Demo</span>
    </div>
    <div class="flex-col-center" style="width: 30%;padding: 100px">
      <h2 style="font-size: 20px">欢迎回来</h2>
      <el-form ref="formRef" :model="form" :rules="formRules">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入账号">
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="form.passWord" placeholder="请输入密码" show-password type="password">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="推荐人" prop="reference">
          <el-input v-model="form.reference" placeholder="请输入推荐人"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="reqLogin()">登录</el-button>
    </div>
  </div>
</template>
<style scoped>
.flex-col-center {
  display: flex;
  flex-direction: column;
  justify-content: center
}
</style>

到此这篇关于Vue Form表单的使用,rules格式校验网络校验,键盘按键监听的文章就介绍到这了,更多相关Vue Form表单rules格式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论