ref()
ref holds a single value, including primitives, in a reactive box you read and write through .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) returns an object with a .value property that Vue tracks. In templates, refs returned from setup are unwrapped automatically, so you write count instead of count.value.
In script code always use .value. refs can hold objects too, and are then deeply reactive.
Note:
Templates unwrap top-level refs, but script code needs .value.
Example: 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
- Forgetting .value in script
- Using .value in templates
- Losing reactivity by copying the raw value
Chapter Summary
- ref wraps any value
- Use .value in script
- Templates unwrap refs
- Works for primitives and objects
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: