setup में Lifecycle Hooks
Composition API में lifecycle hooks onMounted और onUnmounted जैसे functions हैं जिन्हें आप setup के अंदर call करते हैं।
In this page:
Syntax
import { onMounted, onUnmounted } from 'vue';
setup() {
onMounted(() => {
// runs after mounting
});
onUnmounted(() => {
// cleanup
});
}
Setup में Lifecycle Hooks
onMounted, onUpdated, onUnmounted, onBeforeMount, और इनके जैसे import या access करें और इन्हें एक callback pass करें। आप same hook कई बार call कर सकते हैं, जो composables को अपना setup और cleanup logic register करने देता है। created और beforeCreate की जगह खुद setup लेता है।
Note:
same composable में जिसने इन्हें बनाया उसी में timers और listeners onUnmounted में clean up करें।
उदाहरण: Lifecycle hooks in setup
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app"><p>{{ ticks }} ticks</p></div>
<script>
const events = [];
let tickRef;
const app = Vue.createApp({
setup() {
const ticks = Vue.ref(0);
tickRef = ticks;
let timer;
Vue.onMounted(() => { events.push("mounted"); timer = setInterval(() => ticks.value++, 5); });
Vue.onUnmounted(() => { events.push("unmounted"); clearInterval(timer); });
return { ticks };
},
});
app.mount("#app");
setTimeout(() => { app.unmount(); console.log(events.join(" -> "), "| ticks counted while mounted:", tickRef.value > 0); }, 40);
</script>
</body>
</html>
<!-- Output:
console: mounted -> unmounted | ticks counted while mounted: true
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- setup के बाहर hooks call करना
- cleanup भूल जाना
- एक created hook की उम्मीद करना
चैप्टर सारांश
- onMounted, onUpdated, onUnmounted jaise hooks मिलते हैं
- इन्हें setup के अंदर call करें
- कई calls allowed हैं
- setup created की जगह लेता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: