Member-only story
Watching for Changes in Vue.js Component Slot Content
I recently had the need to update the state of a component any time its contents (slot, children, etc.) changed. For context, it’s a form component that tracks the validity state of its inputs.
I thought it would be more straight forward than it was, and I didn’t find a whole lot of content out there. So having a solution I’m satisfied with, I decided to share. Let’s build it out together :)
The following code snippets are written in the Options API format but should work with Vue.js version 2 and version 3 except where specified.
The Setup
Let’s start with a form that tracks its validity state, modifies a class based on the state, and renders it’s children as a <slot/>
.
<template>
<form :class="{ '--invalid': isInvalid }">
<slot />
</form>
</template><script>
export default {
data: () => ({
isInvalid: false,
}),
};
</script>
To update the isInvalid
property, we need to attach an event handler to some event. We could use the “submit” event, but I prefer the “input” event.
Form’s don’t trigger an “input” event, but we can use a pattern called “event delegation“. We’ll attach the listener to the parent element (<form>
) that gets triggered any time the…