App.vue
ChildComp.vue
main.js
<template>
<h2>Example expose Option</h2>
<p>Using the exposed 'createMessage' method from the child component to write a message in the child component:</p>
<input type="text" v-model="inpText" placeholder="Write something">
<button v-on:click="useMet">Use exposed method</button>
<child-comp ref="childComp"/>
</template>
<script>
export default {
data() {
return {
inpText: ''
}
},
methods: {
useMet() {
this.$refs.childComp.createMessage(this.inpText);
}
}
}
</script>
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Message from parent component:</p>
<p id="pEl">{{ message }}</p>
</div>
</template>
<script>
export default {
expose: ['createMessage'],
data() {
return {
message: ' '
}
},
methods: {
createMessage(msg) {
this.message += msg + ' '
}
}
}
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
max-width: 350px;
margin-top: 20px;
}
#pEl {
background-color: lightgreen;
font-family: 'Courier New', Courier, monospace;
}
</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')