虽然Vue使您可以轻松地将属性添加到您的组件中,但有时您需要对允许添加哪些类型的内容进行更大的控制,幸运的是,Vue提供了内置的方式来添加类型检查,验证,默认值和限制。
类型检查
您可以通过添加类型属性来轻松添加类型检查到您的属性定义。
例如,以下组件将可能的输入值限制为数字。
1[label ChildComponent.vue]
2<template>
3 <h2>Numerical Property {{imperfectNumber}}</p>
4</template>
5
6<script>
7export default {
8 props: {
9 imperfectNumber: {
10 type: Number
11 }
12 }
13}
14</script>
1[label ParentComponent.vue]
2<template>
3 <child-component :imperfectNumber="41"></child-component>
4</template>
5
6<script>
7import ChildComponent from './ChildComponent.vue';
8
9export default {
10 components: {
11 ChildComponent
12 }
13}
14</script>
允许的类型值是:
- 对象 - 只允许对象,如 :myProp="{key: 'value'}".
- 数组 - 只允许数组,如 :myProp="[1, 2, 3]".
- 函数只允许函数传输,如 *:myProp="function(test) { return test.toUpperCase() }".
- 字符串 - 只允许字符串,如 :myProp="'Example'"(或更简单地说, myProp="Example"). 函数 - 只允许数值,如 :myProp="103.4".(MKK1) * Boolean - 只允许真或错误
缺陷价值观
您可以通过将所需:真值添加到属性定义中来强制要求属性。
1props: {
2 imperfectNumber: {
3 type: Number,
4 required: true
5 }
6}
或者,您可以为该属性设置默认值,如果没有传输值,则将使用该值。
1props: {
2 imperfectNumber: {
3 type: Number,
4 default: 43
5 }
6}
您甚至可以将其设置为函数,以生成动态默认值!
1props: {
2 imperfectNumber: {
3 type: Number,
4 default: () => Math.random()
5 }
6}
定制验证器
对于更复杂的对象,您还可以添加自定义验证函数. 验证器只是一个函数,它采取输入属性值并返回一个布尔,如果它是有效的,否则是假的。
1props: {
2 imperfectNumber: {
3 type: Number,
4 validator: value => {
5 // Only accepts values that contain the string 'cookie-dough'.
6 return value.indexOf('cookie-dough') !== -1
7 }
8 }
9}
通过将这些属性结合起来,您可以强大地处理几乎任何用户可能扔到您的组件的值,并使其更容易使用理解。