温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2023-03-11 13:59:30 来源:亿速云 阅读:119 作者:iii 栏目:开发技术

本篇内容主要讲解“Vue的子组件props怎么设置多个校验类型”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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.

    <child :content="1"></child>
    
    Vue.component('child',{
                  props:['content'],
                  template: "<div>{{content}}</div>",
              })

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

    参数校验一

    限定参数的类型

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

    如果不满足则会报[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: "<div>{{content}}</div>",
              })

    参数校验三

    自定义校验规则

    Vue.component('child',{
                  props:{
                     content:{
                         type:Number,
                         default:100,
                         required:false,
                         validator:function(value){   //自定义校验的规则
                             return value>5;
                         }
                     }
                  },
                  template: "<div>{{content}}</div>",
              })

    到此,相信大家对“Vue的子组件props怎么设置多个校验类型”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI