vue3 defineprops
时间: 2023-09-21 22:03:48 浏览: 82
Vue 3 introduced a new composition API, and with it comes the `defineProps` function.
In Vue 3, you can use the `defineProps` function to define props for a component when you are using the new composition API. This function allows you to define props and their types, default values, and other options.
Here's an example of how to use `defineProps`:
```javascript
import { defineProps } from 'vue';
export default {
props: {
// ...
},
setup(props) {
// Define props using defineProps
const { propA, propB } = defineProps({
propA: {
type: String,
required: true,
},
propB: {
type: Number,
default: 0,
},
});
// Access the props in the setup function
console.log(propA);
console.log(propB);
// ...
},
};
```
In this example, we import the `defineProps` function from the `vue` package. Inside the `setup` function, we use `defineProps` to define two props: `propA` and `propB`.
`propA` is defined as a required prop of type `String`, while `propB` is defined as an optional prop of type `Number` with a default value of `0`.
We can access these props within the `setup` function by destructuring the returned object from `defineProps`. In this case, we destructure `propA` and `propB` from the result, and then log their values to the console.
Please note that `defineProps` is used specifically in Vue 3's composition API. In Vue 2, you would still use the regular options API to define props.
阅读全文