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之父子组件传值验证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04package.json 文件位置在哪?-icode9专业技术文章分享
- 2024-10-01Craco.js学习:从入门到实践指南
- 2024-10-01Create-React-App学习:入门与实践指南
- 2024-10-01CSS-in-JS学习:从入门到实践指南
- 2024-09-30JSX语法学习:从入门到初步掌握
- 2024-09-30Mock.js学习:入门教程与实战演练
- 2024-09-30React Hooks学习:从入门到实践
- 2024-09-30受控组件学习:React中的基础入门教程
- 2024-09-29JS定时器教程:初学者必看指南
- 2024-09-29JS对象教程:初学者的全面指南