App.vue
CompOne.vue
main.js
<template>
<h1>Lifecycle Hooks</h1>
<button @click="this.activeComp = !this.activeComp">Create component</button>
<div>
<comp-one v-if="activeComp"></comp-one>
</div>
</template>
<script>
export default {
data() {
return {
activeComp: false
}
}
}
</script>
<style scoped>
div {
border: dashed black 1px;
border-radius: 10px;
padding: 20px;
margin: 10px;
width: 400px;
background-color: lightgreen;
}
</style>
<template>
<h2>Form Component</h2>
<p>When this component is added to the DOM tree, the mounted() function is called, and we put the cursor inside the
input element.</p>
<form @submit.prevent>
<label>
<p>
Name: <br>
<input type="text" ref="inpName">
</p>
</label>
<label>
<p>
Age: <br>
<input type="number">
</p>
</label>
<button>Submit</button>
</form>
<p>(This form does not work, it is only here to show the mounted lifecycle hook.)</p>
</template>
<script>
export default {
mounted() {
this.$refs.inpName.focus();
}
}
</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')