Props·续
In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest value. This means you should not attempt to mutate a prop inside a child component. If you do, Vue will warn you in the console:
const props = defineProps(['foo'])
// ❌ warning, props are readonly!
props.foo = 'bar'
export default {
props: ['foo'],
created() {
// ❌ warning, props are readonly!
this.foo = 'bar'
}
}
There are usually two cases where it's tempting to mutate a prop:
- The prop is used to pass in an initial value; the child component wants to use it as a local data property afterwards. In this case, it's best to define a local data property that uses the prop as its initial value:
const props = defineProps(['initialCounter'])
// counter only uses props.initialCounter as the initial value;
// it is disconnected from future prop updates.
const counter = ref(props.initialCounter)
```
```js
export default {
props: ['initialCounter'],
data() {
return {
// counter only uses this.initialCounter as the initial value;
// it is disconnected from future prop updates.
counter: this.initialCounter
}
}
}
```
2. **The prop is passed in as a raw value that needs to be transformed.** In this case, it's best to define a computed property using the prop's value:
```js
const props = defineProps(['size'])
// computed property that auto-updates when the prop changes
const normalizedSize = computed(() => props.size.trim().toLowerCase())
```
```js
export default {
props: ['size'],
computed: {
// computed property that auto-updates when the prop changes
normalizedSize() {
return this.size.trim().toLowerCase()
}
}
}
```
### Mutating Object / Array Props
When objects and arrays are passed as props, while the child component cannot mutate the prop binding, it **will** be able to mutate the object or array's nested properties. This is because in JavaScript objects and arrays are passed by reference, and it is unreasonably expensive for Vue to prevent such mutations.
The main drawback of such mutations is that it allows the child component to affect parent state in a way that isn't obvious to the parent component, potentially making it more difficult to reason about the data flow in the future. As a best practice, you should avoid such mutations unless the parent and child are tightly coupled by design. In most cases, the child should [emit an event](/guide/components/events) to let the parent perform the mutation.
## Prop Validation
Components can specify requirements for their props, such as the types you've already seen. If a requirement is not met, Vue will warn you in the browser's JavaScript console. This is especially useful when developing a component that is intended to be used by others.
To specify prop validations, you can provide an object with validation requirements to the `defineProps()` macro`props` option, instead of an array of strings. For example:
```js
defineProps({
// Basic type check
// (`null` and `undefined` values will allow any type)
propA: Number,
// Multiple possible types
propB: [String, Number],
// Required string
propC: {
type: String,
required: true
},
// Required but nullable string
propD: {
type: [String, null],
required: true
},
// Number with a default value
propE: {
type: Number,
default: 100
},
// Object with a default value
propF: {
type: Object,
// Object or array defaults must be returned from
// a factory function. The function receives the raw
// props received by the component as the argument.
default(rawProps) {
return { message: 'hello' }
}
},
// Custom validator function
// full props passed as 2nd argument in 3.4+
propG: {
validator(value, props) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].includes(value)
}
},
// Function with a default value
propH: {
type: Function,
// Unlike object or array default, this is not a factory
// function - this is a function to serve as a default value
default() {
return 'Default function'
}
}
})
[!TIP] Code inside the
defineProps()argument cannot access other variables declared in<script setup>, because the entire expression is moved to an outer function scope when compiled.
export default {
props: {
// Basic type check
// (`null` and `undefined` values will allow any type)
propA: Number,
// Multiple possible types
propB: [String, Number],
// Required string
propC: {
type: String,
required: true
},
// Required but nullable string
propD: {
type: [String, null],
required: true
},
// Number with a default value
propE: {
type: Number,
default: 100
},
// Object with a default value
propF: {
type: Object,
// Object or array defaults must be returned from
// a factory function. The function receives the raw
// props received by the component as the argument.
default(rawProps) {
return { message: 'hello' }
}
},
// Custom validator function
// full props passed as 2nd argument in 3.4+
propG: {
validator(value, props) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].includes(value)
}
},
// Function with a default value
propH: {
type: Function,
// Unlike object or array default, this is not a factory
// function - this is a function to serve as a default value
default() {
return 'Default function'
}
}
}
}
Additional details:
-
All props are optional by default, unless
required: trueis specified. -
An absent optional prop other than
Booleanwill haveundefinedvalue. -
The
Booleanabsent props will be cast tofalse. You can change this by setting adefaultfor it — i.e.:default: undefinedto behave as a non-Boolean prop. -
If a
defaultvalue is specified, it will be used if the resolved prop value isundefined- this includes both when the prop is absent, or an explicitundefinedvalue is passed.
When prop validation fails, Vue will produce a console warning (if using the development build).
If using Type-based props declarations , Vue will try its best to compile the type annotations into equivalent runtime prop declarations. For example, defineProps<{ msg: string }> will be compiled into { msg: { type: String, required: true }}.
[!TIP] Note Note that props are validated before a component instance is created, so instance properties (e.g.
data,computed, etc.) will not be available insidedefaultorvalidatorfunctions.
Runtime Type Checks
The type can be one of the following native constructors:
StringNumberBooleanArrayObjectDateFunctionSymbolError
In addition, type can also be a custom class or constructor function and the assertion will be made with an instanceof check. For example, given the following class:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
You could use it as a prop's type:
defineProps({
author: Person
})
export default {
props: {
author: Person
}
}
Vue will use instanceof Person to validate whether the value of the author prop is indeed an instance of the Person class.
Nullable Type
If the type is required but nullable, you can use the array syntax that includes null:
defineProps({
id: {
type: [String, null],
required: true
}
})
export default {
props: {
id: {
type: [String, null],
required: true
}
}
}
Note that if type is just null without using the array syntax, it will allow any type.
Boolean Casting
Props with Boolean type have special casting rules to mimic the behavior of native boolean attributes. Given a <MyComponent> with the following declaration:
defineProps({
disabled: Boolean
})
export default {
props: {
disabled: Boolean
}
}
The component can be used like this:
<!-- equivalent of passing :disabled="true" -->
<MyComponent disabled />
<!-- equivalent of passing :disabled="false" -->
<MyComponent />
When a prop is declared to allow multiple types, the casting rules for Boolean will also be applied. However, there is an edge when both String and Boolean are allowed - the Boolean casting rule only applies if Boolean appears before String:
// disabled will be casted to true
defineProps({
disabled: [Boolean, Number]
})
// disabled will be casted to true
defineProps({
disabled: [Boolean, String]
})
// disabled will be casted to true
defineProps({
disabled: [Number, Boolean]
})
// disabled will be parsed as an empty string (disabled="")
defineProps({
disabled: [String, Boolean]
})
// disabled will be casted to true
export default {
props: {
disabled: [Boolean, Number]
}
}
// disabled will be casted to true
export default {
props: {
disabled: [Boolean, String]
}
}
// disabled will be casted to true
export default {
props: {
disabled: [Number, Boolean]
}
}
// disabled will be parsed as an empty string (disabled="")
export default {
props: {
disabled: [String, Boolean]
}
}
