toRef for a single property?toRef. What will be displayed when the button is clicked twice?<script setup> import { reactive, toRef } from 'vue' const state = reactive({ count: 0 }) const countRef = toRef(state, 'count') function increment() { countRef.value++ } </script> <template> <div> <p>Count: {{ countRef.value }}</p> <button @click="increment">Increment</button> </div> </template>
toRef creates a reactive reference to the original property.The toRef creates a reactive reference to state.count. Incrementing countRef.value updates state.count. After clicking twice, the count increases from 0 to 2, so the displayed value is 2.
nameRef.value after modifying the original object?nameRef.value after user.name is changed?<script setup> import { reactive, toRef } from 'vue' const user = reactive({ name: 'Alice', age: 30 }) const nameRef = toRef(user, 'name') user.name = 'Bob' </script>
toRef keeps the reference reactive to the original property.nameRef is a reactive reference to user.name. When user.name changes to 'Bob', nameRef.value also updates to 'Bob'.
toRefs to destructure a reactive object?profile into refs. Which code snippet is correct?const profile = reactive({ firstName: 'John', lastName: 'Doe' })
toRefs returns an object with refs for each property.toRefs returns an object with the same keys as the original reactive object, but each value is a ref. Destructuring with curly braces {} is correct. Using square brackets [] is invalid because toRefs does not return an array.
ageRef.value undefined when using toRef?console.log(ageRef.value) output undefined?<script setup> import { reactive, toRef } from 'vue' const person = reactive({ name: 'Eve' }) const ageRef = toRef(person, 'age') console.log(ageRef.value) </script>
toRef creates a ref for the specified property. If the property does not exist on the reactive object, the ref's value is undefined. Therefore, console.log(ageRef.value) outputs undefined.
toRef and toRefs in Vue 3?toRef and toRefs.toRef creates a reactive reference to a single property of a reactive object. toRefs creates reactive references for all properties of a reactive object and returns them as an object with the same keys.