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

其他教程   发布日期:2023年08月17日   浏览次数:427

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

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

    1. type使用 | 进行隔开

    1. props: {
    2. iconClass: {
    3. type: String | null,
    4. required: true,
    5. default: ""
    6. }
    7. },

    2. 使用数组

    1. props: {
    2. iconClass: [String , null]
    3. },

    3. 使用validator校验函数

    1. props: {
    2. iconClass: {
    3. validator: (value)=> {
    4. const getResult = Object.prototype.toString.call(value)
    5. if(getResult === "[object Null]" || getResult === "[object String]") return true;
    6. },
    7. required: true,
    8. default: ""
    9. },
    10. }

    Vue组件参数校验

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

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

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

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

    参数校验一

    限定参数的类型

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

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

    参数校验二

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

    1. Vue.component('child',{
    2. props:{
    3. content:{
    4. type:Number, //限制参数的类型为Number
    5. default:100, //设置参数的默认值为100
    6. required:false, //是否必须
    7. }
    8. },
    9. template: "<div>{{content}}</div>",
    10. })

    参数校验三

    自定义校验规则

    1. Vue.component('child',{
    2. props:{
    3. content:{
    4. type:Number,
    5. default:100,
    6. required:false,
    7. validator:function(value){ //自定义校验的规则
    8. return value>5;
    9. }
    10. }
    11. },
    12. template: "<div>{{content}}</div>",
    13. })

    以上就是Vue的子组件props怎么设置多个校验类型的详细内容,更多关于Vue的子组件props怎么设置多个校验类型的资料请关注九品源码其它相关文章!