验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Vue的子组件props怎么设置多个校验类型

阅读:1143 来源:乙速云 作者:代码code

Vue的子组件props怎么设置多个校验类型

      vue子组件props设置多个校验值

      1. type使用 | 进行隔开

      props: {
          iconClass: {
            type: String | null,
            required: true,
            default: ""
          }
      },

      2. 使用数组

      props: {
        iconClass: [String , null]
      },

      3. 使用validator校验函数

      props: {
          iconClass: {
              validator: (value)=> {
                const getResult = Object.prototype.toString.call(value)
                if(getResult === "[object Null]" || getResult === "[object String]") return true;
              },
              required: true,
              default: ""
        },
      }

      Vue组件参数校验

      在vue中,当父组件向子组件传递值时.子组件可以对传递过来的值进行参数校验.

      首先我们定义一个子组件child,接受父组件传递过来的值content.

      
      
      Vue.component('child',{
                    props:['content'],
                    template: "
      {{content}}
      ",           })

      注意但我们在content前面加上:,它会认为这是js表达式,所以认为"1"是Number类型而不是String类型.

      参数校验一

      限定参数的类型

      
      
      Vue.component('child',{
                    props:{
                     content: [String,Number],   //这样就限制了参数的类型为String或者Number.
                   },
                    template: "
      {{content}}
      ",           })

      如果不满足则会报[Vue warn]: Invalid prop: type check failed for prop “content”. Expected String, got Number.

      参数校验二

      限定参数的类型,是否必须,默认值

       Vue.component('child',{
                    props:{
                       content:{
                           type:Number,   //限制参数的类型为Number
                           default:100,   //设置参数的默认值为100
                           required:false,  //是否必须
                       } 
                    },
                    template: "
      {{content}}
      ",           })

      参数校验三

      自定义校验规则

      Vue.component('child',{
                    props:{
                       content:{
                           type:Number,
                           default:100,
                           required:false,
                           validator:function(value){   //自定义校验的规则
                               return value>5;
                           }
                       }
                    },
                    template: "
      {{content}}
      ",           })
    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>