Looking to develop a TypeScript wrapper function that can trigger toast notifications using a composition function, following the guidelines outlined in Vue 3.0's Composition API RFC.
In this instance, we are utilizing BootstrapVue v2.0 for toast notifications. In Vue 2, these would be activated through this.$bvToast
as part of the root context:
this.$bvToast.toast('Error occurred', {
title: 'Oh no',
variant: 'danger'
});
The reusable composition function would resemble something like this:
// File: @/util/notify.ts
export function useNotify() {
const notifyError = (title: string, msg: string) => {
// How do we access context.root within a function component without passing it explicitly?
context.root.$bvToast.toast(msg, {
title,
variant: 'danger'
});
};
return { notifyError};
}
export default useNotify;
To apply it, you could follow a pattern similar to this:
// Implement in your functional component:
import { createComponent } from '@vue/composition-api';
import { useNotify} from '@/util/notify';
export default createComponent({
name: 'MyFailingComponent',
setup() {
const { notifyError } = useNotify();
notifyError('Request error', 'An issue occurred with your request, please try again later.');
return {};
}
});