I. Core Positioning: The “Golden Initialization Time” in the Component Lifecycle
created The hook is invoked synchronously after a Vue component instance has been fully created. You can think of it as the crucial moment when the component’s “body” has been constructed but not yet “mounted” to the DOM . created It occurs after reactive data initialization and before the DOM is mounted. This timing determines its core purpose and limitations.
II. Depth Principle: Its Key Role in Initializing the Chain
To understand this created, you must understand the complete initialization process of a Vue instance.
Key takeaway:
During Init State this phase, Vue performed the following key operations, which is created why reactive data is accessible:
- Make
datathe object reactive and proxy it to the instance (this.xxxaccess). - Options include processing
props, etc.methodscomputedwatch - It was the completion of this work that made
createdit the first lifecycle hook that could be safely manipulated.
III. created Core Responsibilities and Best Practices
Based on its characteristic of “data is ready, DOM not generated”, created hooks are best suited for the following types of tasks:
1. Asynchronous data retrieval (first screen optimization)
This is created the most classic application. To minimize the time users spend on the blank screen, asynchronous requests should be initiated as early as possible.
export default {
data() {
return {
userInfo: null,
productList: []
};
},
async created() {
// Initiate multiple asynchronous requests in parallel to optimize first-screen loading
try {
const [userResponse, productsResponse] = await Promise.all([
this.$api.getUserInfo(),
this.$api.getProducts()
]);
this.userInfo = userResponse.data;
this.productList = productsResponse.data;
} catch (error) {
console.error('Data retrieval failed:', error);
}
}
};
Why not mounted retrieve it from there ?
- Earlier triggering : Executing
createdearliermountedallows for earlier data retrieval, shortening the first screen time. - DOM not required : Data retrieval is a logical operation and does not depend on the DOM.
mountedRetrieving data within the DOM will unnecessarily delay the request.
2. Initialize component state and listen for events
export default {
created() {
// Initialize internal state based on props
this.internalValue = this.value || this.defaultValue;
// Initialize non-reactive data (avoid unnecessary reactive overhead)
this.staticConfig = Object.freeze({ MAX_COUNT: 100 });
// Listen to the global event bus
this.$eventBus.$on('global-event', this.handleGlobalEvent);
},
beforeUnmount() {
// Listener must be removed when the component is destroyed to prevent memory leaks!
this.$eventBus.$off('global-event', this.handleGlobalEvent);
}
};
3. Perform a one-time calculation or setting.
export default {
created() {
// Perform a one-time calculation, cache the result in the data
this.initialHash = this.calculateInitialHash(this.initialData);
// Set the timer
this.autoSaveTimer = setInterval(this.autoSave, 30000);
},
beforeUnmount() {
// The timer must be cleared!
clearInterval(this.autoSaveTimer);
}
};
IV. Corresponding entities in composite APIs:setup()
In Vue 3’s composition API, created hooks do not have a direct equivalent because their logic is integrated into setup() functions.
Mental model transformation :
- Optional API :
createdis a specific “point in time”. - Composite API :
setup()The synchronous code at the middle and top levels iscreatedthe logic.
// Optional API
export default {
data() { return { count: 0 }; },
created() {
console.log('created:', this.count); // 0
this.fetchData();
}
};
// Composite API
import { ref, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
// The synchronous code here is equivalent to created
console.log('setup synchronous code:', count.value); // 0
fetchData(); // Equivalent to calling it in created
// If you need the logic for mounted, you need to explicitly use onMounted
onMounted(() => {
console.log('mounted');
});
return { count };
}
};
V. Expert-level Considerations and Performance Optimization
1. Memory leak risk
created Listeners, timers, event listeners, etc. created in the file must be cleaned up in beforeUnmountthe file unmounted .
export default {
created() {
this.intervalId = setInterval(() => {}, 1000);
window.addEventListener('resize', this.handleResize);
},
beforeUnmount() {
clearInterval(this.intervalId);
window.removeEventListener('resize', this.handleResize);
}
};
2. Race conditions between asynchronous operations and component unloading
Setting data in an asynchronous callback can lead to a memory leak if the component is destroyed before the data is returned.
export default {
data() { return { data: null }; },
created() {
let isMounted = true; // Flag
this.$api.getData().then(result => {
if (isMounted) { // Check if the component is still mounted
this.data = result;
}
});
this.$once('hook:beforeUnmount', () => {
isMounted = false; // Marked as false when the component is unmounted
});
}
};
3. Avoid blocking rendering
created It is executed synchronously, and if there are heavy synchronous calculations, it will block the component’s rendering process.
// ❌Avoid: Heavy synchronous calculations
created() {
// This will block component rendering
this.heavyData = this.calculateHeavyStuff();
}
// ✅Recommended: Use computed properties (lazy evaluation) or asynchronous processing
computed: {
heavyData() { return this.calculateHeavyStuff(); }
}
// Or
async created() {
// Use requestIdleCallback or break it down into smaller tasks
this.heavyData = await this.calculateAsync();
}
Summary: created Expert-level understanding
| Dimension | In-depth analysis |
|---|---|
| Positioning | The “golden initialization time” is when data reactive initialization is complete but the DOM has not yet been generated. |
| Core Uses | Asynchronous data retrieval, event listening, one-time initialization, and state setting. |
| Advantages | Earlier versions mounted are better suited for logic that doesn’t rely on the DOM, optimizing the first screen display. |
| Limitations | Unable to manipulate the DOM, asynchronous callbacks need to handle race conditions caused by component destruction. |
| Composite API | Integrated into setup() the synchronous execution part of the function |
| Performance is key | Avoid synchronous blocking and promptly clean up side effects to prevent memory leaks. |
This can created be considered the “data preparation phase” of a component. All DOM-independent initialization work is completed in this phase, laying a solid foundation for subsequent rendering and interaction. Understanding its precise position in the Vue initialization process will help you write more efficient and robust Vue applications.