Consider this composable that accepts a parameter and returns a reactive value:
import { ref } from 'vue'
export function useCounter(start) {
const count = ref(start)
function increment() {
count.value++
}
return { count, increment }
}In a component, we use it like this:
const { count, increment } = useCounter(5)
increment()
increment()
console.log(count.value)What will be logged?
import { ref } from 'vue' export function useCounter(start) { const count = ref(start) function increment() { count.value++ } return { count, increment } } const { count, increment } = useCounter(5) increment() increment() console.log(count.value)
Think about how many times increment() is called and what count starts at.
The composable useCounter starts the count at 5. Each call to increment() adds 1. Called twice, count becomes 7.
Which of these Vue composable definitions correctly accepts a parameter initialValue and returns a reactive value initialized with it?
Remember to initialize ref with the parameter and return it properly.
Option A correctly takes initialValue as parameter, initializes value with ref(initialValue), and returns it inside an object.
Option A uses initialValue without parameter, causing error.
Option A uses reactive on a primitive, which is incorrect.
Option A tries to assign to a const variable, causing error.
Look at this composable:
import { ref } from 'vue'
export function useToggle(initial) {
let state = ref(initial)
function toggle() {
state = !state
}
return { state, toggle }
}When used, calling toggle() does not update state.value. Why?
import { ref } from 'vue' export function useToggle(initial) { let state = ref(initial) function toggle() { state = !state } return { state, toggle } }
Check how the toggle function changes state.
The toggle function assigns a boolean directly to state, replacing the ref object. It should update state.value instead.
Given this composable:
import { ref } from 'vue'
export function useStepCounter(start, step) {
const count = ref(start)
function advance() {
count.value += step
}
return { count, advance }
}And this usage:
const { count, advance } = useStepCounter(10, 3)
advance()
advance()
advance()
console.log(count.value)What is logged?
import { ref } from 'vue' export function useStepCounter(start, step) { const count = ref(start) function advance() { count.value += step } return { count, advance } } const { count, advance } = useStepCounter(10, 3) advance() advance() advance() console.log(count.value)
Count starts at 10 and increases by 3 each advance call.
Starting at 10, three advances add 3 each: 10 + 3 + 3 + 3 = 19.
In Vue, why is it better to pass parameters to a composable function rather than hardcoding values inside it?
Think about reusability and flexibility.
Passing parameters allows the composable to work with different inputs, making it reusable and easier to test. Hardcoding limits flexibility.