onValue callback for props #681
davidhernandeze
started this conversation in
General
Replies: 1 comment
-
You can have a tiny utility function for that: import { watch, toRef } from "vue";
export function onFirstValue(something, fn) {
const somethingRef = toRef(something)
if (somethingRef.value != null) {
fn(somethingRef.value)
return
}
const stopWatching = watch(somethingRef, newValue => {
if (newValue != null) {
stopWatching()
fn(newValue)
}
})
} And use it like: const props = defineProps(['myProp'])
onFirstValue(
() => props.myProp,
firstValue => {
console.log(firstValue)
}
) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Add the ability to trigger an action when a prop value is first set. I found this is a very common scenario when you want a component to render a loading state while waiting for the parent to pass the first value of a prop. The child component receives a null value at first, and waits for the prop to change to render its loaded state. If the component receives a not null value from the beggining, the callback is called after onMounted hook.
Beta Was this translation helpful? Give feedback.
All reactions