props传值强校验validator

父组件给子组件通常通过props传值,如果需要做一些强校验则可以使用validator

如父组件传入一个propType参数,规定只能传入’text’, 'number’或者’letter’其中一种就可以这么写:

props: {
	propType: {
		type: String,
		default:  'text',
		validator() {
			return ['text', 'number','letter'].indexOf(propType) > -1
		}
 	}
}

又或者你想传入一个参数,但是想限制它的长度,那你也可以使用validator进行强校验

props: {
	lintLength: {
		type: Array,
		default: () => [],
		validator() {
			return lintLength.length < 6
		}
 	}
}
### UniApp 使用 Props 进行父子组件 在 Uni-app 中,`props` 是一种单向下行的数据绑定机制,允许父组件向子组件递数据。这种通信方式简单直观,适用于大多数场景下的父子组件交互。 #### 父组件向子组件递数据 当父组件需要向子组件递静态或动态属性时,可以利用 `props` 实现这一功能。具体来说,在定义子组件时声明接受哪些外部输入作为其配置项;而在实例化该子组件的地方,则按照 HTML 属性的形式指定这些即可[^1]。 ```html <!-- ParentComponent.vue --> <template> <view class="parent"> <!-- 将 parentMessage 绑定到 child 的 prop 上 --> <ChildComponent :message="parentMessage"></ChildComponent> </view> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentMessage: 'Hello, I am the father component!' } } } </script> ``` ```html <!-- ChildComponent.vue --> <template> <view class="child"> {{ message }} </view> </template> <script> // 声明接收来自父级的消息 export default { props: ['message'] }; </script> ``` 上述代码展示了如何创建两个 Vue 单文件组件——ParentComponent 和 ChildComponent,并通过 `props` 让前者能够把消息发送给后者显示出来[^2]。 #### 子组件更新父组件状态 虽然 `props` 主要用于从上至下流动的信息流,但在某些情况下也需要让子组件影响父组件的状态变化。这时通常会结合 `$emit()` 方法来触发自定义事件通知上级作出相应调整[^5]。 例如: ```html <!-- ChildComponent.vue --> <template> <view class="child"> <button @click="sendMessageToFather">Click me to change father's value!</button> </view> </template> <script> export default { methods: { sendMessageToFather() { this.$emit('updateValue', 'New Value From Son'); } } } </script> ``` ```html <!-- ParentComponent.vue --> <template> <view class="parent"> <p>Father says: {{ fatherValue }}</p> <!-- 接收并处理子组件发出的 updateValue 事件 --> <ChildComponent @updateValue="(newValue) => fatherValue = newValue"></ChildComponent> </view> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { fatherValue: '' }; } } </script> ``` 这段示例说明了怎样设置监听器捕获特定命名空间内的任何更改请求,从而同步反映在整个应用程序的不同部分之中[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值