Svelte Components — Two-way Binding (bind:) and computed properties ($:) are Great!
I really like Svelte, it is much simpler for me to comprehend than Vue. I guess at 65 my brain can’t handle as much as it used to.
I plan on rewriting my Airport Weather app from Vue to Svelte and posting the results here. In the meantime, I am creating some useful components.
I’m using the W3.CSS framework (which I also like because it is css only), but it does not have anything to do with the workings of my components, so just ignore the classes or substitute yours.
A few rules about Svelte components
- Components must start with a Capital Letter.
- Components must be imported into the parent
- Components can take a value from the parent and return it using the bind: directive
W3input - My first component wraps the HTML Input tag with a label and input. It defaults to type=”text”, maxlength=50, rows=5. It can also handle type=”textarea” for multiline input.
All of the exported variables are available to the control passed as props from the parent. Variables without export are local to the component. If the variable is assigned a value, then it will be the default if no prop is passed.
All of the props are one way to the component, except for bind:value. bind: is a special modifier that creates a two-way variable.
Another great directive is $: This is a computed directive where the code is executed anytime the variables change. So
$: if (!value) value = "";
ensures that an undefined or null value is converted to an empty string.
The parent component includes the child component as an HTML tag.
Again, by using bind:value, name and phone will be updated on each keypress in the child component.
In my next post, I’ll show you how to create radio button and checkbox groups in a reusable Svelte component. This is a little trickier but it works.