Vue Form表单的使用,rules格式校验网络校验,键盘按键监听

Form表单

rules格式校验

  • 可以在validator中进行网络请求,实现网络校验
js 复制代码
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(校验规则)
js 复制代码
<el-form ref="formRef" :model="form" :rules="formRules">
js 复制代码
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('/')
    }
  })
}

键盘监听

js 复制代码
onMounted(() => {
  console.log("页面加载")
  document.addEventListener('keyup', onkeyup)
})

onBeforeUnmount(() => {
  document.removeEventListener('keyup', onkeyup)
})

function onkeyup(e) {
  if (e.key === 'Enter') {
    reqLogin()
  }
}

完整代码

js 复制代码
<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>
相关推荐
sunly_30 分钟前
Flutter:flutter_screenutil屏幕适配
前端·javascript·flutter
俸涛努力学前端35 分钟前
ajax (一)
开发语言·前端·javascript·笔记·ajax
糯米w1 小时前
【前端】excel文件对比
前端·javascript·excel
南城巷陌1 小时前
node.js中实现router模块化管理
前端·javascript·node.js·express.router
new Vue()2 小时前
ES6中Promise的使用场景
开发语言·前端·javascript
爱写代码的派大星2 小时前
el-table :span-method 合并单元格(2.0)
前端·javascript·vue.js
夫琅禾费米线2 小时前
CSS 设置宽高的单位概览
前端·javascript·css
chusheng18402 小时前
Java 基于SpringBoot+Vue的家政服务管理平台
java·vue.js·spring boot·家政服务·家政服务平台
余生H3 小时前
transformer.js(四): 模型接口介绍
前端·javascript·深度学习·transformer