I built a simple Banner component which is imported in _layout.html. It exposes 5 methods (dismiss, info, warning, ...).
Currently I'm using the store to keep track of these methods as in _layout.html below.
_layout.html
<main>
<Banner ref:banner/>
<svelte:component this={child.component} {...child.props} />
</main>
<script>
export default {
components: {
Banner: '../components/Banner.html',
},
oncreate() {
this.store.set({
Banner: {
dismiss: this.refs.banner.dismiss,
danger: this.refs.banner.danger,
info: this.refs.banner.info,
success: this.refs.banner.success,
warning: this.refs.banner.warning
}
})
}
}
So I can call them from any part of the app like so:
blog.html
...
this.store.get().Banner.success('Post saved!')
} catch (err) {
this.store.get().Banner.danger(err)
}
...
This is working fine however I wonder if this is the best Svelte way to do it.
Well I'm not sure of a better Svelte way. What you did looks good to me. You could
oncreate() {
Object.assign(this, this.refs.banner);
//or assign the exposed methods to the root component in any way
}
...
this.root.success('Post saved!');
...
Since all elements have reference to the root component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With