因业务需要,项目涉及大量表单提交,并且校验时会展示相应的错误样式(如下图),目前移动端的ui框架中并未找到相应的通用组件,如果按照原生的方法则需要给每一条数据项分别添加,代码会出现冗余,影响开发效率,所以需要实现组件化

具体代码如下:
1 <template>
2 <div class="valid-input" :class="{'error':error}">
3 <slot></slot> //使用时具体数据项
4 <img src="../assets/error.png" v-show="error">
5 </div>
6 </template>
7
8 <script>
9 export default {
10 name: "Valid",
11 props:{
12 max:{
13 type:Number,
14 required:false //控制可输入数据最大长度
15 },
16 min:{
17 type:Number,
18 required:false //控制可输入数据的最小长度
19 },
20 validator:{
21 type:Function,
22 required:false //根据业务需要具体定义校验方法
23 },
24 content:{
25 required:true
26 },
27 30 },
31 watch:{ //监测数据变化
32 content(val){
33
34 if (val&&val!=""){
35 if (this.min && val.length < this.min){
36 this.error = true;
37 }else if (this.max && val.length > this.max){
38 this.error = true;
39 }else if (this.validator && !this.validator(val)){
40 this.error = true;
41 }else {
42 this.error = false;
43 }
44 }else{
45 48 }
49 }
50 },
51 data(){
52 return {
53 error:false
54 }
55 }
56 }
57 </script>
58
59 <style scoped lang="scss">
60 .valid-input{
61 position: relative;
62 line-height: 13.33vw;
63 img{
64 width: 4.53vw;
65 margin: 0 1vw;
66 vertical-align: middle;
67 }
68 }
69 .error>*{
70 color: #ff4b33;
71 &::placeholder{
72 color: #ff4b33;
73 }
74 &:-moz-placeholder{
75 color: #ff4b33;
76 }
77 &::-webkit-input-placeholder{
78 color: #ff4b33;
79 }
80 &:-ms-input-placeholder{
81 color: #ff4b33;
82 }
83 } // 可根据业务自定义错误的样式
84 </style>
使用时:
<tr>
<td>手机号码</td>
<td>
<valid
:validator="validator.phoneValid"
:content="validate.tel"
>
<input type="tel" v-model="applicantInfo.tel" placeholder="请输入您的手机号码" @change="telChange"/>
</valid>
</td>
</tr>
input 在change事件发生时,将值赋值于校验的对象
telChange(){
this.validate.tel = this.applicantInfo.tel;
},
validator 绑定的是所在项的单独的校验规则
validator:{
idValid:this.idValid,
phoneValid:isPhoneNum, //公共方法中定义
},