App.vue
ChildComp.vue
main.js
<template>
<h2>Example $emit() Method</h2>
<p>Message received from child component:</p>
<p id="pElMsg">{{ message }}</p>
<child-comp v-on:message-sent="receiveEmit" />
</template>
<script>
export default {
data() {
return {
message: ' '
}
},
methods: {
receiveEmit(msg) {
this.message = msg;
}
}
}
</script>
<style>
#pElMsg {
background-color: lightgreen;
padding: 10px;
margin: 0;
max-width: 350px;
display: inline-block;
font-family: 'Courier New', Courier, monospace;
font-weight: bold;
}
</style>
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Write something, and send the message up to the parent component using the $emit() method.</p>
<input type="text" v-model="message" placeholder="write something..">
<button v-on:click="send">Send</button>
</div>
</template>
<script>
export default {
data() {
return {
message: null
}
},
methods: {
send() {
this.$emit('message-sent',this.message);
}
}
}
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
max-width: 350px;
margin-top: 20px;
}
input {
display: block;
margin-bottom: 15px;
}
</style>
import { createApp } from 'vue'
import App from './App.vue'
import ChildComp from './components/ChildComp.vue'
const app = createApp(App)
app.component('child-comp', ChildComp)
app.mount('#app')