Performance: Composable accepting parameters
This affects how efficiently Vue manages reactive state and re-renders components when composables receive parameters.
import { ref } from 'vue'; export function useCounter(initial) { const count = ref(initial); // No watch on parameter, parameter used only once return { count }; }
import { ref, watch } from 'vue'; export function useCounter(initial) { const count = ref(initial); watch(() => initial, (newVal) => { count.value = newVal; }); return { count }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Watching parameter changes inside composable | Multiple reactive updates | Multiple reflows on parameter change | Higher paint cost due to frequent updates | [X] Bad |
| Using parameter only once as initial value | Single reactive update | Single reflow on state change | Lower paint cost with fewer updates | [OK] Good |
What is the main purpose of passing parameters to a Vue composable function?
Which of the following is the correct way to define a composable that accepts a parameter initialCount?
function useCounter(???) {
const count = ref(initialCount)
return { count }
}initialCount must be declared inside the parentheses as initialCount.Given this composable and usage, what will be logged?
import { ref } from 'vue'
function useGreeting(name) {
const greeting = ref(`Hello, ${name}!`)
return { greeting }
}
const { greeting } = useGreeting('Alice')
console.log(greeting.value)name parameter, so the greeting string becomes "Hello, Alice!".greeting is a ref, so to get the string, we use greeting.value, which logs "Hello, Alice!".Identify the error in this composable that accepts a parameter start:
import { ref } from 'vue'
function useTimer(start) {
const time = ref(start)
function increment() {
time++
}
return { time, increment }
}.value property, so you cannot increment the ref itself.time.value++ instead of time++.You want a composable useFilteredList that accepts an array and a filter function as parameters. Which implementation correctly applies the filter reactively?
import { computed } from 'vue'
function useFilteredList(list, filterFn) {
const filtered = computed(() => ??? )
return { filtered }
}What should replace ????
list parameter is expected to be a ref(array) for proper reactivity in Vue composables.computed, access the array value with list.value.filter(filterFn) to apply the filter reactively whenever the list changes.Pass the test and this pattern moves unknown