vue props扩展-参数验证

	props参数验证
	
	不符合设定参数形式,会报警告但不会终止程序
    
    type类型:
    	String、Number、Boolean、Array、Object、Date、Function、Symbol
    
    0、自定义构造函数:内部通过 instanceof 来进行检查确认
			如:
				function Person (firstName, lastName) {
				  this.firstName = firstName
				  this.lastName = lastName
				}
				你可以使用:
				Vue.component('blog-post', {
				  props: {
				    author: Person	验证author的值是否是通过new Person创建的。
				  }
				})
				
	1、验证参数类型
		将原本的props:[xx]替换成
		props:{
			参数名:首字母大写的类型,
			参数名:[类型1,类型2,...]	多个可能的类型
		}

	2、设置参数默认值(即不传参数也能显示)
		props:{
			参数:{
				type:参数类型,
				default:默认值(只能设置基本数据类型)
			}
		}

		设置复杂类型参数默认值(如数组等)
		props:{
			参数:{
				type:参数类型,
				default:function()
				{
					return xx
				}
			}
		}
	
	3、设置必传参数
		props:{
			参数:{
				type:参数类型,
				required:true
			}
		}
		
 	4、设置自定义验证规则,返回布尔值
 		props:{
 			参数:{
 				validator:function(v){
 					return 判断后的布尔值
 				}
 			}
 		}
 		如:
 		    propF: {
		      validator: function (value) {
		       		这个值必须匹配下列字符串中的一个
		        return ['success', 'warning', 'danger'].indexOf(value) !== -1
		      }
		    }

代码示例:
子组件:

<template>
	<div>
		子组件
		{{msg}}
		{{age}}
		{{name}}
		{{nick}}
		{{address}}
		{{sex}}

		<ul>
			<li v-for='num in sex'>{{num}}</li>
		</ul>


		<button @click='send'>传给父组件</button>

	</div>
</template>

<script>
export default{
	name:'B',
	data()
	{
		return{

		}
	},
	props:{
		msg:String,
		age:Number,
		name:String,
		nick:{
			type:String,
			default:'nick2'
		},
		address:{
			type:String,
			required:true
		},
		sex:{
			type:Array,
			default:function(){
				return [1,2,3]
			}
		}
	},
	methods:{
		send()
		{
			this.$emit('info','来自子组件');
		}
	}
}
</script>

<style lang='css'>
<style>

父组件:

<template>
	<div>
		父组件
		<B msg='aaaa'  @info='receive' name='jeff' :age=18 />
		{{msg}}
	</div>
</template>

<script>
import B from './B'
export default{
	name:'A',
	data()
	{
		return{
			msg:''
		}	
	},
	methods:{
		receive(data)
		{
			this.msg=data
		}
	},
	components:{
		B
	}

}
</script>

<style lang='css'>
<style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值