toRef()
toRef creates a ref that stays linked to one property of a reactive object.
In this page:
Syntax
import { reactive, toRef } from 'vue';
const state = reactive({ property: value });
const propRef = toRef(state, 'property');
toRef()
toRef(obj, "key") returns a ref whose value reads and writes that property of the source. Changes flow both ways. toRefs does the same for every property, which lets you destructure a reactive object without losing reactivity, and is handy when returning state from composables.
Note:
Use toRefs when you want to destructure or return a reactive object's properties.
Example: toRef()
<!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>{{ name }} / {{ user.name }}</p>
</div>
<script>
Vue.createApp({
setup() {
const user = Vue.reactive({ name: "Ada", age: 36 });
const name = Vue.toRef(user, "name");
name.value = "Grace";
const { age } = Vue.toRefs(user);
age.value++;
console.log("linked back:", user.name, user.age);
return { user, name };
},
}).mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: Grace / Grace
console: linked back: Grace 37
-->
Live Example
Related Topics
Common Mistakes
- Destructuring reactive objects directly
- Expecting toRef to copy the value
- Forgetting .value on the resulting ref
Chapter Summary
- toRef links to one property
- toRefs links to all properties
- Changes flow both ways
- Keeps reactivity when destructuring
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: