【发布时间】:2020-02-23 01:36:56
【问题描述】:
我想创建一个用 TypeScript 编写的可重复使用的包装函数,用于通过使用 组合函数 来触发 toast 通知,如Vue 3.0 的当前规范:Composition 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 {};
}
});
【问题讨论】:
标签: typescript vue.js bootstrap-vue vuejs3 vue-composition-api