我想创建可重用的包装函数写在打字稿用于通过使用触发 toast 通知复合函数,如 Vue 3.0 的当前规范中所定义:组合 API RFC.
此示例使用 BootstrapVue v2.0 toast 组件。对于 Vue 2,它将通过以下方式调用this.$bvToast
Vue组件实例注入在根上下文中:
this.$bvToast.toast('Error happened', {
title: 'Oh no',
variant: 'danger'
});
这个类似服务的组合函数看起来很像这样:
// File: @/util/notify.ts
export function useNotify() {
const notifyError = (title: string, msg: string) => {
// How to access context.root as in a function component, without passing it to this function?
context.root.$bvToast.toast(msg, {
title,
variant: 'danger'
});
};
return { notifyError};
}
export default useNotify;
并且会像这样使用:
// Use 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', 'There was an error processing your request, please try again later.');
return {};
}
});