App.vue
ChildComp.vue
main.js
<template>
<h2>Example expose Option</h2>
<p>Only the 'message' data property is listed in the 'expose' option, so the 'createMessage' method from the child component is not available, and will not work:</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);
}
},
mounted() {
this.$refs.childComp.message = 'Initial message!';
}
}
</script>
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Message from parent component:</p>
<p id="pEl">{{ message }}</p>
</div>
</template>
<script>
export default {
expose: ['message'],
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')