Options बनाम Composition API
Vue एक component organise करने के दो तरीके offer करता है: named sections वाला Options API, और functions वाला Composition API।
In this page:
Syntax
// Options API
export default {
data() { return { count: 0 }; },
methods: { increment() { this.count++; } }
}
// Composition API
setup() {
const count = ref(0);
return { count };
}
Options बनाम Composition API
Options API code को option type से group करता है (data, methods, computed)। Composition API इसे setup के अंदर feature से group करता है, ref, computed, और इनके जैसे इस्तेमाल करते हुए, जो logic reuse करना आसान बनाता है। दोनों Vue 3 में काम करते हैं और identical behaviour produce कर सकते हैं।
Note:
आप एक project में दोनों styles mix कर सकते हैं।
उदाहरण: Options vs Composition API
<!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">
<options-counter></options-counter>
<composition-counter></composition-counter>
</div>
<script>
const app = Vue.createApp({});
app.component("options-counter", {
data() { return { n: 1 }; },
computed: { double() { return this.n * 2; } },
template: "<p>Options: {{ n }} x2 = {{ double }}</p>",
});
app.component("composition-counter", {
setup() {
const n = Vue.ref(1);
const double = Vue.computed(() => n.value * 2);
return { n, double };
},
template: "<p>Composition: {{ n }} x2 = {{ double }}</p>",
});
app.mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: Options: 1 x2 = 2Composition: 1 x2 = 2
-->
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. #}
आम गलतियां
- यह सोचना कि एक API deprecated है
- this और setup variables को गलत तरीके से mix करना
- setup से values return करना भूल जाना
चैप्टर सारांश
- Options API: data, methods, computed इस्तेमाल करता है
- Composition API: ref और computed के साथ setup
- दोनों Vue 3 में supported हैं
- Composition API logic reuse करने में मदद करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: