Vue 'emits' Option
Example
Using the emits
option to declare which custom events that are emitted from the component.
export default {
emits: ['custom-event'],
methods: {
notifyParent() {
this.$emit('custom-event','Hello! ')
}
}
}
Run Example »
See more examples below
Definition and Usage
The emits
option is used to document what custom events a component emits.
The emits
option is not required, which means that a component can emit events without defining them inside the emits
option.
Even though the emits
option is not required, it is still recommended to have, so that other programmers can easily see what the component emits.
When the emits
option is given as an array, the array just consists of the names of the emits as strings. (See the example above.)
When the emits
option is given as an object, a property name is the name of an emit, and the value is a validator function if it has one, or 'null' if the emit does not have a validator function. (See the example below.)
More Examples
Example
Using props as objects with options, so that the default food description is shown when it is not provided by the parent component.
FoodItem.vue
:
<template>
<div>
<h2>{{ foodName }}</h2>
<p>{{ foodDesc }}</p>
</div>
</template>
<script>
export default {
props: {
foodName: {
type: String,
required: true
},
foodDesc: {
type: String,
required: false,
default: 'This is the food description...'
}
}
};
</script>
App.vue
:
<template>
<h1>Food</h1>
<p>Food description is not provided for 'Pizza' and 'Rice', so the default description is used.</p>
<div id="wrapper">
<food-item
food-name="Apples"
food-desc="Apples are a type of fruit that grow on trees."/>
<food-item
food-name="Pizza"/>
<food-item
food-name="Rice"/>
</div>
</template>
<style>
#wrapper {
display: flex;
flex-wrap: wrap;
}
#wrapper > div {
border: dashed black 1px;
flex-basis: 120px;
margin: 10px;
padding: 10px;
background-color: lightgreen;
}
</style>
Run Example »
Related Pages
Vue Tutorial: Vue $emit() Method
Vue Tutorial: Vue Props
Vue Reference: Vue $props Object
Vue Reference: Vue $emit() Method