vue之父子组件传值验证

2021/7/22 6:10:19

本文主要是介绍vue之父子组件传值验证,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

普通父子组件传值

const app = Vue.createApp({
    data(){
        return{
            message:'hello world',
            num:110
        }
    },
    template:'<div>{{message}} <test :num="num"></test></div>',
});
app.component('test',{
    props:['num'],
    template:`<div>{{ typeof num}}</div>`
})
app.mount('#app')

带校验传值

const app = Vue.createApp({
    data(){
        return{
            message:'hello world',
            num:110
        }
    },
    template:'<div>{{message}} <test :num="num"></test></div>',
});
app.component('test',{
    props:{
        num:String
    },
    template:`<div>{{ typeof num}}</div>`
})
app.mount('#app')

此时传值为string类型,但是父组件定义的num是数字类型,因此控制台就会提示:
[Vue warn]: Invalid prop: type check failed for prop “num”. Expected String with value “110”, got Number with value 110.

当把 num:110 改为字符串 num:“110” 验证成功

支持的类型:Number、String、Boolean、Array、Object、Function、Symbol
required:必填
default:默认值,当父组件不传值时,使用默认值

const app = Vue.createApp({
    data(){
        return{
            message:'hello world',
            num:"hello"
        }
    },
    template:'<div>{{message}} <test ></test></div>',
});
app.component('test',{
    props:{
        num:{
            type:String,
            required:true,
            default:"nihao"
        }
    },
    template:`<div>{{ typeof num}}</div>`
})
app.mount('#app')

控制台:

vue@next:1312 [Vue warn]: Missing required prop: "num" 
  at <Test> 
  at <App>

validator验证

const app = Vue.createApp({
    data(){
        return{
            message:'hello world',
            num: 1235
        }
    },
    template:'<div>{{message}} <test :num="num"></test></div>',
});
app.component('test',{
    props:{
        num:{
            type:Number,
            required:true,
            default:520,
            validator: function(num){
                return num<1000;
            }
        }
    },
    template:`<div>{{ num }}</div>`
})
app.mount('#app')

此时传入的数是1235,大于1000,控制台报

[Vue warn]: Invalid prop: custom validator check failed for prop "num". 
  at <Test num=1235 > 
  at <App>


这篇关于vue之父子组件传值验证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程