The menu card can now show a name and a price from its props. But when its Add button is clicked, who adds to the cart? Not the card. The cart belongs to the parent, and props are read-only.
So the card has to tell the parent. It does this by emitting: the child tells its parent "something just happened here". That message is called an event. Props go down from parent to child, events go up from child to parent. Picture a customer in front of a menu card at Mrs. Sri's stall pressing an "Add" bell. The menu card doesn't hold the cart, so it only rings the bell and calls out "Fried Rice, $15". The cashier who hears the bell writes it into the cart. In Vue, the menu card is the child, the ring of the bell is the event, and the cashier is the parent.
The child sends an event with emit
Here is MenuCard.vue, which sends the event add when its button is clicked:
<!-- MenuCard.vue -->
<script setup>
const props = defineProps({ name: String, price: Number })
const emit = defineEmits(["add"])
function clickAdd() {
emit("add", props.name, props.price)
}
</script>
<template>
<div class="card">
<h3>{{ name }}</h3>
<p>${{ price }}</p>
<button @click="clickAdd">Add</button>
</div>
</template>
defineEmits(["add"])declares which events this component may send. LikedefineProps,defineEmitsis a compiler macro, so it needs no import.defineEmitsreturns a function for sending events. The variable name is up to you.emitis only the name people usually use.emit("add", props.name, props.price): the first argument is the event name, the rest is the payload, the data sent along with it.- In the template you can also call
$emitdirectly:<button @click="$emit('add', name, price)">.
The parent listens with @
Here is the parent, App.vue, listening for the add event from two cards:
<!-- App.vue -->
<script setup>
import { ref } from "vue"
import MenuCard from "./MenuCard.vue"
const count = ref(0)
const total = ref(0)
function addToCart(name, price) {
count.value++
total.value += price
console.log("Added to cart:", name)
}
</script>
<template>
<MenuCard name="Fried Rice" :price="15" @add="addToCart" />
<MenuCard name="Iced Tea" :price="5" @add="addToCart" />
<p>Cart: {{ count }} item, ${{ total }}</p>
</template>
| Click | Payload that arrives | count |
total |
Console |
|---|---|---|---|---|
| start | 0 | 0 | ||
| Add on Fried Rice | "Fried Rice", 15 |
1 | 15 | Added to cart: Fried Rice |
| Add on Fried Rice | "Fried Rice", 15 |
2 | 30 | Added to cart: Fried Rice |
| Add on Iced Tea | "Iced Tea", 5 |
3 | 35 | Added to cart: Iced Tea |
@add="addToCart"is short forv-on:add, just like@clickfor a click. A parent listens for other events the same way, for example anupdateevent with@update="...".- The payload arrives as the handler's arguments, in the same order as in
emit:name, thenprice. - The handler can also be a short statement written inline:
@add="count++". In a short statement,$eventholds the first payload value, not an event object as with@click. - If the parent doesn't attach
@add, nobody is listening. The event just disappears, with no error and no warning.
Props down, events up
In the Props lesson, the child wasn't allowed to change the prop stock. Emitting solves that: the child reports, and the parent changes the data. Here is a Buy 1 button:
<!-- MenuCard.vue, in the template -->
<small>Stock: {{ stock }}</small>
<button @click="$emit('buy')">Buy 1</button>
<!-- App.vue, in the template -->
<MenuCard name="Chicken Noodles" :stock="stock" @buy="stock--" />
When Buy 1 is clicked:
- The child sends the event
buy. - The parent runs
stock--, which lowers its ownstockref. - The new number flows back down to the child through
:stock.
The data still has a single owner: the parent.
v-model on your own component. v-model on a component uses the same pattern: a prop goes down, an event whose name starts with update: goes up. Since Vue 3.4, defineModel() writes that pattern for you. Here is a portion counter with - and + buttons:
<!-- PortionCount.vue -->
<script setup>
const portions = defineModel({ default: 1 })
</script>
<template>
<button @click="portions--">-</button>
{{ portions }}
<button @click="portions++">+</button>
</template>
<!-- App.vue, in the template -->
<PortionCount v-model="rice" />
defineModel()returns a ref. When the child changesportions, Vue sends the eventupdate:modelValue, then the parent changes its ownriceref. The parent stays the owner, so this is not changing a prop. We tried it on Vue 3.5.45:ricestarts at 2, two clicks on + make it 4, then one click on - makes it 3.- More than one
v-model? Give it a name:defineModel("spice")in the child,v-model:spice="spiceLevel"in the parent. - Before Vue 3.4, you wrote this pattern yourself: a
modelValueprop plusemit("update:modelValue", newValue).
📌 Event names and validation
- An event name is written camelCase in
emit("addToCart"), but in the parent you listen for it in kebab-case:@add-to-cart. Vue treats them as the same event. - To check the payload, use the object form:
defineEmits({ add: (price) => price > 0 }). The function receives the payload, then returnstrueorfalse. If it returnsfalse, in development mode the console writes[Vue warn]: Invalid event arguments: event validation failed for event "add".The event is still sent; it's only a warning. - Declare every event you send. For example, take a child whose root element (its outermost element) is a
<button>and that sendsclickwithout declaring it. The parent's@clickhandler then runs twice: once from the emit, and once from the real click on the<button>, because Vue passes an undeclared@clickon to the child's root element. The next lesson covers this passing on. If you declareclick(defineEmits(["click"]), oremits: ["click"]in the exercise editor), the handler runs only once.
.vue files and the exercise editor
In the exercise editor, a child is written as an object with the emits option, and placed with <component :is>, as in the Props lesson:
const count = ref(0)
const total = ref(0)
function addToCart(name, price) {
count.value++
total.value += price
console.log("Added to cart:", name)
}
const MenuCard = {
props: { name: String, price: Number },
emits: ["add"],
template: `
<div class="card">
<h3>{{ name }}</h3>
<p>{{ "$" + price }}</p>
<button @click="$emit('add', name, price)">Add</button>
</div>
`,
}
---template---
<div>
<component :is="MenuCard" name="Fried Rice" :price="15" @add="addToCart" />
<component :is="MenuCard" name="Iced Tea" :price="5" @add="addToCart" />
<p>Cart: {{ count }} item, ${{ total }}</p>
</div>
| In a .vue file | In the exercise editor |
|---|---|
const emit = defineEmits(["add"]) |
the emits: ["add"] option |
emit("add", ...) in the script |
$emit('add', ...) in the child's template, or emit from setup(props, { emit }) |
<MenuCard @add="..." /> |
<component :is="MenuCard" @add="..." /> |
- The editor's main component has no parent, so
defineEmitsin its script sends nowhere. Emitting is always written in the child. - This lesson's exercises use this editor form: a child object with
emits,$emitin its template, and@add(or@subtract) on<component>. The checker reads the numbers on the page before and after a button is clicked. The checker also looks for those three parts in your code.
⚠️ The button gets clicked, but the parent's number is off
- The child only sends an event. What changes the number, like
stockin the example orcountin the first exercise, is the parent, not the child itself. emit("add")without@addon the parent does nothing, with no message at all.- A handler that overwrites the value, like
count.value = 1, is right on the first click but wrong on the second. In the first exercise, the checker clicks twice, then checks that the number is2. Writecount.value++. - In the second exercise, the number starts at
5, not 0. Before any click, it is5. After -1 is clicked, it is4. Starting again from 5, after +1 is clicked, it is6.
TL;DR: Emitting sends a message (an event) from child to parent. The child declares its events with const emit = defineEmits(["add"]), then calls emit("add", name, price). The arguments after the event name are called the payload: the data sent along. The parent listens with @add="handler", and the payload arrives as the handler's arguments. If the parent doesn't listen, the event disappears with no error. Props down, events up: the child reports, the parent changes the data. In the exercise editor, a child is written as an object with emits: ["add"] and $emit(...) in its template, then placed with <component :is>.
⚡ The child sends an event
Write:
<!-- MenuCard.vue -->
<script setup>
const props = defineProps({ name: String, price: Number })
const emit = defineEmits(["add"])
function clickAdd() {
emit("add", props.name, props.price)
}
</script>
Meaning: Emitting is how a child sends a message (an event) to its parent. defineEmits(["add"]) declares the events this component may send, and returns the sending function, here emit. The first argument of emit is the event name; the rest is the payload, the data sent along with it.
⚡ The parent listens with @
Write:
<MenuCard name="Fried Rice" :price="15" @add="addToCart" />
Guess first: if the parent doesn't attach @add, what happens when MenuCard sends the add event?
Nothing. The event just disappears, with no error and no warning.
Meaning: @add is short for v-on:add, just like @click. The parent listens for the add event from MenuCard, then runs addToCart. The payload arrives as the handler's arguments, in the same order as in emit: addToCart(name, price).
⚡ Props down, events up
Write:
<!-- MenuCard.vue, in the template -->
<button @click="$emit('buy')">Buy 1</button>
<!-- App.vue, in the template -->
<MenuCard name="Chicken Noodles" :stock="stock" @buy="stock--" />
Meaning: $emit sends an event straight from the template. The child only reports, through the event buy, and the parent lowers its own stock ref. The new number then flows back down to the child through :stock.