reactive() का उपयोग
reactive एक पूरे object को deeply reactive बनाता है ताकि इसकी properties बदलना view update कर दे।
In this page:
Syntax
import { reactive } from 'vue';
const state = reactive({ property: value });
state.property = new_value;
reactive()
reactive एक object को एक Proxy में wrap करता है जो हर property पर reads और writes track करता है, nested वाली समेत। आप .value के बिना सीधे properties access करते हैं।
पूरा object replace न करें या इसे destructure न करें, क्योंकि दोनों reactivity खो देते हैं; destructure करते वक्त toRefs इस्तेमाल करें।
Note:
reactive सिर्फ objects के साथ काम करता है, numbers या strings जैसी primitive values के साथ नहीं।
उदाहरण: reactive()
<!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>{{ state.name }} has {{ state.items.length }} items</p>
<button @click="add">Add</button>
</div>
<script>
Vue.createApp({
setup() {
const state = Vue.reactive({ name: "Cart", items: ["pen"] });
const add = () => state.items.push("ink");
return { state, add };
},
}).mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: Cart has 2 itemsAdd
console: Cart has 2 items
-->
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. #}
आम गलतियां
- पूरे reactive object को reassign करना
- properties destructure करना और reactivity खो देना
- primitives के लिए reactive इस्तेमाल करना
चैप्टर सारांश
- reactive एक object को deeply proxy करता है
- किसी .value की ज़रूरत नहीं
- carelessly replace या destructure न करें
- Destructure करने के लिए toRefs इस्तेमाल करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: