Given that you mentioned this as a simplified scenario, I will approach it as a more complex issue with three methods.
Utilize ComputedRef
For further details, refer to: https://vuejs.org/guide/essentials/computed.html#basic-example
export const applyOpeningHours = (
flight: Ref<FlightOption | null>,
identifier: string,
isEnabled?: boolean
) => {
return {
show: computed(() => {
if (flight.value) return false
return true
}),
gate: computed(() => {...}),
}
}
This provides show
and gate
as a ComputerRef
, which is akin to show.value
Using @vueuse/core
can streamline the process
export const applyOpeningHours = (
flight: Ref<FlightOption | null>,
identifier: string,
isEnabled?: boolean
) => {
return toReactive(computed(() => {
if (!flight.value) {
return {
show: false,
gate: "",
};
}
return {
show: ...,
gate: ...
}
}))
}
const flight = ref<FlightOption | null>(null);
const { show: showOpeningHours } = toRefs(applyOpeningHours(
flight,
props.identifier,
true
));
Employ Reactive
export const applyOpeningHours = (
flight: Ref<FlightOption | null>,
identifier: string,
isEnabled?: boolean
) => {
const result = reactive({ <default value> })
watchEffect(() => { // or watch, watchPostEffect, watchSyncEffect
if (!flight.value) {
result.show = false
result.gate = ""
}
...
})
return result
}
const flight = ref<FlightOption | null>(null);
const { show: showOpeningHours } = toRefs(applyOpeningHours(
flight,
props.identifier,
true
));
Utilize Ref
export const applyOpeningHours = (
flight: Ref<FlightOption | null>,
identifier: string,
isEnabled?: boolean
) => {
const show = ref(false)
const gate = ref("")
watch(flight, flight => { // or watchEffect
if (!flight) {
show.value = false
gate.value = ""
}
...
}, { immediate: true })
return { show, gate }
}