日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

(el-Form)操作(不使用 ts):Element-plus 中 Form 表單組件校驗(yàn)規(guī)則等的使用

作者:獅子座的男孩 更新時(shí)間: 2023-08-15 編程語(yǔ)言

Ⅰ、Element-plus 提供的 Form 表單組件與想要目標(biāo)情況的對(duì)比:

1、Element-plus 提供 Form 表單組件情況:

其一、Element-plus 自提供的 Form 代碼情況為(示例的代碼):

在這里插入圖片描述


// Element-plus 自提供的代碼:
// 此時(shí)是使用了 ts 語(yǔ)言環(huán)境,但是我在實(shí)際項(xiàng)目中并沒(méi)有使用 ts 語(yǔ)言和環(huán)境;

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="Password" prop="pass">
      <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="Confirm" prop="checkPass">
      <el-input
        v-model="ruleForm.checkPass"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="Age" prop="age">
      <el-input v-model.number="ruleForm.age" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >Submit</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const checkAge = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('Please input digits'))
    } else {
      if (value < 18) {
        callback(new Error('Age must be greater than 18'))
      } else {
        callback()
      }
    }
  }, 1000)
}

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  pass: '',
  checkPass: '',
  age: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  age: [{ validator: checkAge, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>


代碼地址(直接點(diǎn)擊下面 url 跳轉(zhuǎn)):https://element-plus.gitee.io/zh-CN/component/form.html#自定義校驗(yàn)規(guī)則

其二、頁(yè)面的顯示情況為:

在這里插入圖片描述

2、目標(biāo)想修改后的情況:

// 此時(shí)雖然頁(yè)面的樣式有些變化,但實(shí)際上的用 form 語(yǔ)法或校驗(yàn)規(guī)則等都是沒(méi)有變化的;

在這里插入圖片描述

Ⅱ、實(shí)現(xiàn) Form 表單組件達(dá)到目標(biāo)效果變化的過(guò)程:

1、 Form 表單組件成功引入 vue3 項(xiàng)目的過(guò)程(去除了 ts 的語(yǔ)法):

其一、代碼(以 age 為例):

<script setup>

import {ref} from 'vue'

const ruleFormRef = ref(null)   // 注意:一定要定義 form 表單中 ref 的 ruleFormRef 的值,否則會(huì)一直報(bào)錯(cuò);

const ruleForm = ref({
  pass: "",
  checkPass: "",
  age: '',
  // size: '4000',
  // ip: '0.0.0.0'
})


// 重置的操作;
const resetForm = (val) => {
  debugger
  if (!val) return
  val.resetFields()  // resetFields 函數(shù):是將表單字段的值重置為其默認(rèn)值;
}


// age 的規(guī)則是:讓 age 的值,不能為空,為數(shù)字,且數(shù)字值不小于 18;
const checkAge = (rule, value, callback) => {
  if (!value) {  // 此時(shí)是判空,如果 age 中為空,就拋出該提示信息;
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {   // 此時(shí)是:判斷 age 中輸入的值是否是數(shù)字,如果不是數(shù)字就拋出該提示信息;
      callback(new Error('Please input digits'))
    } else {
      if (value < 18) { // 此時(shí)是:判斷 age 中輸入的數(shù)字是否小于 18,如果小于 18,就拋出該提示信息;
        callback(new Error('Age must be greater than 18'))
      } else {
        callback()
      }
    }
  }, 1000)
}


// 注意:在 rules 方法中 validator 屬性后面的方法,一定要定義在 rules 函數(shù)前,否則會(huì)報(bào)錯(cuò);
const rules = ref({
  age: [
    { validator: checkAge, trigger: 'blur' }
  ],
})


// 此時(shí)是:提交表單的操作;
const submitForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid) => {  // 注意:此時(shí)使用的是 ruleFormRef.value,而僅寫(xiě) ruleFormRef 是拿不到值且會(huì)報(bào)錯(cuò)的;
    if (valid) {   // 注意:只有當(dāng)所有的規(guī)則都滿足后,此時(shí)的 valid 的值才為 true,才能執(zhí)行下面的值;
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

</script>

<template>
  <div class="project_background">
    <div class="my_project">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="Password" prop="pass">
          <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="Confirm" prop="checkPass">
          <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="Age" prop="age">
          <el-input v-model.number="ruleForm.age" />
        </el-form-item>
        <!-- <el-form-item label="大小" prop="log_size">
          <el-tooltip class="box-item" effect="light" content="請(qǐng)?zhí)顚?xiě) 500 到 4000 的數(shù)" placement="top">
            <el-input v-model="ruleForm.size" placeholder="請(qǐng)輸入"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="IP" prop="log_service_ip">
          <el-tooltip class="box-item" effect="light" content="請(qǐng)?zhí)顚?xiě)合法的 ip 地址" placement="top">
            <el-input v-model="ruleForm.ip" placeholder="請(qǐng)輸入"/>
          </el-tooltip>
        </el-form-item>  -->
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"><el-icon :size="20" style="margin-right: 5px;"><CircleCheckFilled /></el-icon>Submit</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
 .project_background {
  margin: 30px auto;
  background-color: #e6f1f9;
  box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 40px 0px;
  .my_project {
    margin: 20px;
  }
 }
</style>

其二、效果展示:

A、輸入的值不是數(shù)字會(huì)報(bào)錯(cuò):

在這里插入圖片描述
B、輸入的值的小于 18 也會(huì)報(bào)錯(cuò):

在這里插入圖片描述
C、只有正確的值才能成功提交:

在這里插入圖片描述

Ⅲ、修改 Form 表單組件達(dá)到目標(biāo)效果的展示:

1、整體的代碼(即:總的代碼):


// 此時(shí)是去除 ts 的 Element-plus 組件的 vue3 語(yǔ)法的代碼:

<script setup>

import {ref} from 'vue'

const ruleFormRef = ref(null)   // 注意:一定要定義 form 表單中 ref 的 ruleFormRef 的值,否則會(huì)一直報(bào)錯(cuò);

const ruleForm = ref({
  pass: "",
  checkPass: "",
  age: ''
})


// 重置的操作;
const resetForm = (val) => {
  debugger
  if (!val) return
  val.resetFields()  // resetFields 函數(shù):是將表單字段的值重置為其默認(rèn)值;
}


// Password 的規(guī)則是:讓 Password 的輸入值,不能為空,且若 Confirm 的輸入值不為空時(shí),在 Password 的輸入值后在執(zhí)行一遍 Confirm 的規(guī)則;
const validatePass = (rule, value, callback) => {
  if (value === '') {  // 此時(shí)是判空,如果 Password 中為空,就拋出該提示信息;
    callback(new Error('Please input the password'))
  } else {
    if (ruleForm.value.checkPass !== '') {  // 此時(shí)是:判斷 Confirm 輸入的值是否為空;
      if (!ruleFormRef.value) return  // 只要 Confirm 中有輸入,此時(shí)的 !ruleFormRef.value 的布爾值為 false;
      ruleFormRef.value.validateField('checkPass', () => null) // validateField 是用于對(duì)表單中的字段進(jìn)行驗(yàn)證的方法,來(lái)確保數(shù)據(jù)的正確性;
                                                               // 個(gè)人理解是:在 Confirm 中有輸入與 Password 的輸入對(duì)比的操作,因此可以理解為:對(duì) 'checkPass'(即:Confirm)
                                                               // 進(jìn)行監(jiān)聽(tīng),即:有執(zhí)行了一遍 Confirm 的驗(yàn)證(確定:通過(guò) debugger 驗(yàn)證了猜想);
    }
    callback()
  }
}

// Confirm 的規(guī)則是:讓 Confirm 的輸入值,不能為空,且與 Password 的輸入值要保持一致;
const validatePass2 = (rule, value, callback) => {
  if (value === '') {  // 此時(shí)是判空,如果 Confirm 中為空,就拋出該提示信息;
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.value.pass) { // 此時(shí)是:判斷 Confirm 輸入的值是否與 Password 輸入的值相同,若不相同,就拋出該提示信息;
    callback(new Error("Two inputs don't match!"))
  } else { // 只有 Confirm 輸入的值與 Password 輸入的值相同,才沒(méi)問(wèn)題(前提是:Passwork 與 Confirm 中都有值);
    callback()
  }
}


// age 的規(guī)則是:讓 age 的值,不能為空,為數(shù)字,且數(shù)字值不小于 18;
const checkAge = (rule, value, callback) => {
  if (!value) {  // 此時(shí)是判空,如果 age 中為空,就拋出該提示信息;
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {   // 此時(shí)是:判斷 age 中輸入的值是否是數(shù)字,如果不是數(shù)字就拋出該提示信息;
      callback(new Error('Please input digits'))
    } else {
      if (value < 18) { // 此時(shí)是:判斷 age 中輸入的數(shù)字是否小于 18,如果小于 18,就拋出該提示信息;
        callback(new Error('Age must be greater than 18'))
      } else {
        callback()
      }
    }
  }, 1000)
}


// 注意:在 rules 方法中 validator 屬性后面的方法,一定要定義在 rules 函數(shù)前,否則會(huì)報(bào)錯(cuò);
const rules = ref({
  // form 表單前面有沒(méi)有小紅星,取決于有沒(méi)有 'required: true' 的屬性,如果有這個(gè)屬性頁(yè)面就有小紅星,而沒(méi)有這個(gè)屬性就沒(méi)有小紅星;
  pass: [
    { required: true, validator: validatePass, trigger: 'blur' }
  ],
  checkPass: [
    { validator: validatePass2, trigger: 'blur' }
  ],
  age: [
    { validator: checkAge, trigger: 'blur' }
  ],
})


// 此時(shí)是:提交表單的操作;
const submitForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid) => {  // 注意:此時(shí)使用的是 ruleFormRef.value,而僅寫(xiě) ruleFormRef 是拿不到值且會(huì)報(bào)錯(cuò)的;
    if (valid) {   // 注意:只有當(dāng)所有的規(guī)則都滿足后,此時(shí)的 valid 的值才為 true,才能執(zhí)行下面的值;
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

</script>

<template>
  <div class="project_background">
    <div class="my_project">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="Password" prop="pass">
          <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="Confirm" prop="checkPass">
          <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="Age" prop="age">
          <el-input v-model.number="ruleForm.age" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"><el-icon :size="20" style="margin-right: 5px;"><CircleCheckFilled /></el-icon>Submit</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
 .project_background {
  margin: 30px auto;
  background-color: #e6f1f9;
  box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 40px 0px;
  .my_project {
    margin: 20px;
  }
 }
</style>


2、整體效果的展示:

在這里插入圖片描述

Ⅳ、小結(jié):

其一、哪里有不對(duì)或不合適的地方,還請(qǐng)大佬們多多指點(diǎn)和交流!
其二、若有轉(zhuǎn)發(fā)或引用本文章內(nèi)容,請(qǐng)注明本博客地址(直接點(diǎn)擊下面 url 跳轉(zhuǎn)) https://blog.csdn.net/weixin_43405300,創(chuàng)作不易,且行且珍惜!
其三、有興趣的話,可以多多關(guān)注這個(gè)專欄(Vue(Vue2+Vue3)面試必備專欄)(直接點(diǎn)擊下面 url 跳轉(zhuǎn)):https://blog.csdn.net/weixin_43405300/category_11525646.html?spm=1001.2014.3001.5482

原文鏈接:https://blog.csdn.net/weixin_43405300/article/details/132224475

  • 上一篇:沒(méi)有了
  • 下一篇:沒(méi)有了
欄目分類
最近更新