defineProps
时间: 2023-09-25 16:16:10 浏览: 43
`defineProps` 是 Vue 3 中的一个函数,用于定义组件的 props 属性。它的作用类似于 Vue 2 中的 `props` 选项,但是使用起来更加灵活和方便。
使用 `defineProps` 定义 props 属性时,需要传入一个对象,对象的属性名表示 prop 的名称,属性值表示 prop 的类型。例如:
```javascript
import { defineProps } from 'vue'
export default {
props: defineProps({
msg: String,
count: {
type: Number,
default: 0
},
isShow: Boolean
})
}
```
上面的代码中,使用 `defineProps` 定义了一个包含三个 props 属性的对象,分别是 `msg`、`count` 和 `isShow`。其中,`msg` 的类型为 `String`,`count` 的类型为 `Number`,并且设置了默认值为 `0`,`isShow` 的类型为 `Boolean`。
使用 `defineProps` 定义 props 属性后,可以通过组件实例的 `$props` 属性访问到所有的 props 值。例如:
```html
<template>
<div>
<p>{{ msg }}</p>
<p>{{ count }}</p>
<p>{{ isShow }}</p>
</div>
</template>
<script>
import { defineProps } from 'vue'
export default {
props: defineProps({
msg: String,
count: {
type: Number,
default: 0
},
isShow: Boolean
}),
mounted() {
console.log(this.$props.msg)
console.log(this.$props.count)
console.log(this.$props.isShow)
}
}
</script>
```
在上面的代码中,使用 `$props` 访问了组件实例的 `msg`、`count` 和 `isShow` props 值,并在组件 `mounted` 钩子函数中打印了这些值。