search
HomeWeb Front-endJS Tutorial总结elementUI表单验证的踩坑解决方法

总结elementUI表单验证的踩坑解决方法

Mar 17, 2023 pm 04:22 PM
javascriptfront endelementui

本篇文章给大家带来了关于elementUI的相关知识,其中主要跟大家聊一聊我在实现elementUI的表单验证时都遇到哪些坑,顺便记录分享一下?感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。

最近做了一个需要表单填写的项目,需要做很多表单验证工作,学到了新知识,为了避免以后会踩到同样的坑,就在这里记录起来。 

我总结之后,有四个要注意:

1.在v-for的列表下,form表单的验证该如何精确触发
2.对list进行增删操作的时候,如何确保视图正确更新
3.自定义验证规则的时候,如何知道操作的数据在数据结构中的准确位置
4.对象深层的key验证该如何触发

这是要操作的列表:1678847828783.png

  <div
          class="boxItem"
          v-for="(item, index) in formData.boxList"
          :key="item.guid"
        >
         <el-form-item
              :label="keytolabel(subkey)"
              v-for="(subItem, subkey) in item"
              :key="subkey"
              :prop="`boxList.${index}.${subkey}`"
         </el-form-item>
  </div>

第一个问题的解决方案:

我们在遍历form-item的时候,就需要prop属性,根据官方文档的说明,prop是表单域 model 字段,在使用 validate、resetFields 方法的情况下,该属性是必填的。正是这个属性,可以让组件知道触发的时机。其中的触发逻辑没有去深入研究。

  :prop="`boxList.${index}.${subkey}`"

在rules这里sybkey要和rules的key值对应上才可以正常触发

     rules: {
        screenlength: [{ validator: lengthhandler, trigger: "blur" }],
       }

如上述所示,根据list的数量进行遍历行数,再根据item来遍历列数。每一列都有不定数量的key值,那么在这里的我们需要给prop指定到准确的位置,大概模式就是父key.行数.列key,简单地来说,就是要将这个值所在的数据结构位置告诉element组件。

根据我的猜测,element表单组件触发验证的逻辑是监听这个值的变化,根据给定的触发条件(change,input,blur,focus等等),符合触发条件就去对比是否发生值的变化,然后根据验证规则去做相应的提示。

第二个问题的解决方案:

我们在遍历form-item的时候,vue会要求必须有一个key,这样可以正确更新视图。那么这一个key最大的特点是要操持唯一。我的方案是给key值生成一个唯一id,或者new Date().getTime()生成一个时间戳,当我们对列表进行操作的时候,就会正确更新视图了。

例如:当我们触发第一和第二的item验证的时候

image.png再去删除第二个item,视图就会在删除之后,验证提示会删除

image.png

如果不是唯一key,例如使用index做key值,那么这个key是不会变化的,删除第二个item就会出现以下情况

image.png

当发生这种情况的时候,你应该考虑的是vue的视图更新规则

第三个问题的解决方案:

自定义验证规则在官方文档有详细的说明,这一块就不用细说了,但是里面的触发逻辑需要根据情况来修改代码。例如总数是根据前面的长和高相乘公式得出的,那么我们需要每次在长和高的值变化的时候,就需要去计算总数,然后根据规则去进行提示。

设置一个currentIndex,在长和高的输入框组件上定义focus事件,每次触发就说明输入框在操作,这一行就被操作的一行数据,那么在定义验证的时候就知道是哪一行了

  // 在组件focus的时候,就说明想操作这个组件,提前将位置记录,以便于数据验证
    focus(data) {
      this.currentIndex = data.index;
    },

当然,代码还是要根据具体交互来编写

第四个问题的解决方案:

很多时候,我们都只是对表层key进行验证,所以如果需要验证对象的深层可以的时候,我们需要做特殊处理,和第一个问题的处理方式类似,但又不完全相同。

// 要验证的数据结构:
    formData:{
        sendcard:{
        sendcardsource:""
        }
    }
    //prop:组件属性
      <el-form-item  prop="sendcard.sendcardsource">
      </el-form-item>   
      
   //rules:规则设置
        rules: {
        // 发送卡
        "sendcard.sendcardsource": [commonRule],
        }

这里的特点就是需要在rules属性定义一个验证验证规则,prop的值要跟rules的值对应上才可以触发。这里的特点是,对象和对象的可能会有相同的key,所以这样做是可以在rules设置一个唯一的触发key值。

总结:

其实我有个疑问,第一个问题和第四个问题的解决是不是可以用同一种解决方式的?

推荐学习:《JavaScript视频教程》《vue.js视频教程

The above is the detailed content of 总结elementUI表单验证的踩坑解决方法. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!