vue3 props emit
时间: 2023-08-26 07:11:36 浏览: 122
vue 自定义组件的写法与用法详解
Vue 3 introduces a few changes in the way props and emit are handled compared to Vue 2. Here's how you can use props and emit in Vue 3:
1. Props:
- In Vue 3, props are declared using the `props` option inside the component setup. You can define the props as an object with the desired prop names as keys and their respective types as values.
- For example, to define a prop named "message" of type String, you can do:
```javascript
import { defineComponent } from 'vue';
export default defineComponent({
props: {
message: {
type: String,
required: true, // optional, if the prop is required
default: 'Hello!', // optional, default value for the prop
},
},
});
```
2. Emitting Events:
- In Vue 3, emitting events is done through the `emit` function that is available inside the component's setup.
- To emit an event, you call `emit` with the event name and any additional payload data.
- For example, to emit an event named "update" with a payload of "newValue", you can do:
```javascript
import { defineComponent } from 'vue';
export default defineComponent({
methods: {
updateValue(newValue) {
this.$emit('update', newValue);
},
},
});
```
Remember to import the necessary functions (`defineComponent`, etc.) from the 'vue' package. I hope this helps!
阅读全文