1. Vue3 life cycle innovation features
Compared with Vue2, Vue3 brings a more flexible life cycle management method through the Composition API. passonBeforeMount
When the function registers the hook, it actually passesinjectHook
Method registers the callback function to the component instancehmr
in the attribute.
In Vue3 application development, the life cycle hook function plays a crucial role. They allow developers to execute custom logic at all stages from creation to destruction of components, providing developers with fine control over the component life cycle. Understanding and proficiently applying these hook functions is the key to developing efficient and robust Vue3 applications.
// Vue3 source code fragment (packages/runtime-core/src/)
export function injectionHook(
type: LifecycleHook,
hook: Function & { __weh?: Function },
target: ComponentInternalInstance | null
) {
const hooks = target[type] || (target[type] = [])
(hook)
}
2. Create a stage hook function
2.1 beforeCreate
-
Trigger timing: Before the component instance is created, the component's
data
、computed
、methods
The properties such as the ones have not been initialized and cannot be accessedthis
。 -
Use scenarios: Although in actual development
beforeCreate
Use less, but in some scenarios where common logic is required before component creation, such as recording component creation logs, you can write code here.
2.2 created
-
Trigger timing: Called after the component instance is created, at this time
data
、computed
、methods
Then, it has been initialized, can be passedthis
Access the properties and methods of the component, but the DOM is not mounted yet. - Use scenarios: Commonly used to initialize data, such as reading data from local storage and assigning responsive data to components, or performing some simple computational attribute initialization. It is also suitable to initiate some asynchronous data requests here that do not require dependency on the DOM.
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('');
const fetchData = async () => {
const response = await fetch('/api/data');
const data = await ();
= ;
};
fetchData();
</script>
3. Mounting stage hook function
3.1 beforeMount
- Trigger timing: Called before the component is mounted to the DOM, at which point the template has been compiled, but it has not been mounted to the actual DOM node.
- Use scenarios: Can be used to make final adjustments to templates or data before mounting, such as modifying some properties of the DOM that is about to be mounted. However, since the DOM has not been mounted yet, it is not very meaningful to operate the DOM directly.
3.2 mounted
-
Trigger timing: The component is called after successfully mounted to the DOM, and can be passed
$el
Access the real DOM element, or userefs
Access subcomponents and elements. - Use scenarios: Commonly used in scenarios where DOM is required, such as initializing third-party plug-ins (such as chart libraries, rich text editors, etc.), these plug-ins usually need to be initialized in the presence of a real DOM. Some calculations or data processing that rely on the DOM structure can also be performed at this time.
3.3 Third-party library integration specifications
Take ECharts integration example:
<template>
<div ref="chartContainer"></div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import Chart from '';
const chartContainer = ref(null);
onMounted(() => {
if () {
new Chart(, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}
]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
});
</script>
4. Update stage hook function
4.1 beforeUpdate
-
Trigger timing: Called before component data is updated, at this time the component's
data
Have changed, but the DOM has not been updated yet. - Use scenarios: Can be used to perform some preparation before data updates, such as saving the status of the current DOM for comparison or recovery after updates.
4.2 updated
- Trigger timing: Called after the component data is updated and the DOM re-rendering is completed.
-
Use scenarios: Suitable for some operations that rely on the updated DOM state, such as recalculating some layout information based on the new DOM structure, or further style adjustments to the updated DOM. But it needs to be noted that
updated
When operating DOM in hook functions, avoid falling into a dead loop, because modifying data again may trigger updates again.
<template>
<div @click="updateData">
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref, onBeforeUpdate, onUpdated } from 'vue';
const message = ref('initial message');
const updateData = () => {
= 'Updated message';
};
onBeforeUpdate(() => {
('Data will be updated soon, current message:', );
});
onUpdated(() => {
('Data has been updated, DOM has been re-rendered');
});
</script>
5. Uninstallation stage hook function
5.1 beforeUnmount
- Trigger timing: Called before the component instance is uninstalled, the component still exists and can access the component's properties and methods.
- Use scenarios: It is often used to clean up some side effects created by components during operation, such as clearing timers, unbinding event listeners, etc., to avoid memory leaks.
5.2 unmounted
- Trigger timing: The component instance is called after being successfully uninstalled. At this time, the component and all its subcomponents have been removed from the DOM, and the component-related event listeners, timers, etc. have been cleaned up.
- Use scenarios: In theory, there is no need to perform complex operations here, but it can be used to record log information related to component uninstallation.
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref, onBeforeUnmount, onUnmounted } from 'vue';
const message = ref('component content');
let timer;
const startTimer = () => {
timer = setInterval(() => {
('Timer is running');
}, 1000);
};
startTimer();
onBeforeUnmount(() => {
clearInterval(timer);
('Component is about to be uninstalled, clear the timer');
});
onUnmounted(() => {
('Component uninstalled');
});
</script>
6. Common misunderstandings and solutions
Problem phenomenon | Cause analysis | Solution |
---|---|---|
Get DOM as null in mounted | Asynchronous rendering delay | Use nextTick() |
Memory leak | Uncleaned event monitoring | Create a clean function registry |
Repeat request | Previous request was not canceled | Using AbortController |
Written at the end
hello! Hello everyone, I am Code_Cracke, a friend who loves programming. Here, I will share some practical development skills and experiences. If you are also passionate about programming, please follow and communicate and learn together!If you have any questions, suggestions or unique insights about this article, please leave a message in the comment area. Whether it is discussing technical details or sharing project experience, we can make progress together.