Consider a Vue 3 component that displays a number doubled. Which option shows the correct output when using a computed property versus a method?
<script setup> import { ref, computed } from 'vue' const count = ref(2) const doubleComputed = computed(() => count.value * 2) function doubleMethod() { return count.value * 2 } </script> <template> <div> <p>Computed: {{ doubleComputed }}</p> <p>Method: {{ doubleMethod() }}</p> </div> </template>
Both computed properties and methods can return values, but computed caches results until dependencies change.
Both computed and method return the doubled value of count (2 * 2 = 4). The output shows 4 for both.
In Vue 3, what happens to the output when count changes rapidly and you use a computed property versus a method to double it?
<script setup> import { ref, computed } from 'vue' const count = ref(1) const doubleComputed = computed(() => count.value * 2) function doubleMethod() { return count.value * 2 } // Imagine count.value changes rapidly </script> <template> <div> <p>Computed: {{ doubleComputed }}</p> <p>Method: {{ doubleMethod() }}</p> </div> </template>
Think about caching behavior of computed properties versus methods.
Computed properties cache their result and only recalculate when dependencies change. Methods run every time the component renders.
Which option shows the correct way to define a computed property that returns the uppercase version of a reactive name?
import { ref, computed } from 'vue' const name = ref('vue') // Define computed property here
Remember computed takes a function returning a value.
Option B correctly uses an arrow function returning the uppercase string. Option B is missing parentheses. Option B lacks a return statement. Option B accesses name directly instead of name.value.
Given this Vue 3 component snippet, why does the method cause performance issues compared to a computed property?
<script setup> import { ref } from 'vue' const count = ref(0) function double() { console.log('Calculating double') return count.value * 2 } </script> <template> <button @click="count++">Increment</button> <p>Double: {{ double() }}</p> </template>
Think about when methods run in Vue templates.
Methods run every time the component renders, so the console.log runs repeatedly, causing performance issues. Computed properties cache results and only recalculate when dependencies change.
You have a Vue 3 component that performs an expensive calculation based on reactive data. Which approach is best to optimize performance and why?
Consider caching and reactive updates.
Computed properties cache their results and only update when dependencies change, making them ideal for expensive calculations. Methods recalculate every render, which is inefficient. Watchers add complexity and regular functions outside reactivity won't update automatically.