ref() का उपयोग
ref primitives समेत एक single value एक reactive box में hold करता है जिसे आप .value से पढ़ते और लिखते हैं।
In this page:
Syntax
import { ref } from 'vue';
const name = ref(initial_value);
name.value = new_value; // use .value in script
ref()
ref(value) एक .value property वाला एक object return करता है जिसे Vue track करता है। Templates में, setup से returned refs automatically unwrap होते हैं, इसलिए आप count.value की बजाय count लिखते हैं।
script code में हमेशा .value इस्तेमाल करें। refs objects भी hold कर सकते हैं, और तब deeply reactive होते हैं।
Note:
Templates top-level refs unwrap करते हैं, लेकिन script code को .value चाहिए।
उदाहरण: ref()
<!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>Count: {{ count }}</p>
<button @click="inc">+1</button>
</div>
<script>
Vue.createApp({
setup() {
const count = Vue.ref(0);
const inc = () => { count.value++; };
console.log("initial .value:", count.value);
return { count, inc };
},
}).mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => console.log("rendered:", document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: Count: 1+1
console: initial .value: 0
console: rendered: Count: 1
-->
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. #}
आम गलतियां
- script में .value भूल जाना
- templates में .value इस्तेमाल करना
- raw value copy करके reactivity खोना
चैप्टर सारांश
- ref किसी भी value को wrap करता है
- script में .value इस्तेमाल करें
- Templates refs unwrap करते हैं
- Primitives और objects दोनों के लिए काम करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: