App.vue
CompOne.vue
main.js
<template>
<h1>The 'beforeMount' Lifecycle Hook</h1>
<p>We can see the console.log() message from the 'beforeMount' lifecycle hook, but the text change we try to do to the 'pEl' paragraph DOM element does not work, because the 'pEl' paragraph DOM element does not exist yet at this stage.</p>
<button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
<div>
<comp-one v-if="activeComp"></comp-one>
</div>
</template>
<script>
export default {
data() {
return {
activeComp: false
}
}
}
</script>
<style>
#app > div {
border: dashed black 1px;
border-radius: 10px;
padding: 10px;
margin-top: 10px;
background-color: lightgreen;
}
#pEl {
background-color: lightcoral;
display: inline-block;
}
</style>
<template>
<h2>Component</h2>
<p>This is the component</p>
<p ref="pEl" id="pEl">We try to access this text from the 'beforeMount' hook.</p>
</template>
<script>
export default {
beforeMount() {
console.log("beforeMount: This is just before the component is mounted.");
this.$refs.pEl.innerHTML = "Hello World!"; // <-- We cannot reach the 'pEl' DOM element at this stage
}
}
</script>
import { createApp } from 'vue'
import App from './App.vue'
import CompOne from './components/CompOne.vue'
const app = createApp(App)
app.component('comp-one', CompOne)
app.mount('#app')