在main.js我有这样的事情:
import { myUtilFunc} from './helpers';
Object.defineProperty(Vue.prototype, '$myUtilFunc', { value: myUtilFunc });
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我可以访问myUtilFunc整个应用程序this.$myUtilFunc
但是,setup()如果我无法访问 Vue 3中的方法,我该如何实现this?
我想创建一个用TypeScript编写的可重用包装器函数,用于通过使用组合函数触发 Toast 通知,如 Vue 3.0 的当前规范:组合 API RFC 中所定义。
此示例使用 BootstrapVue v2.0 toast 组件。使用 Vue 2,它将通过根上下文中的this.$bvToastVue 组件实例注入来调用:
this.$bvToast.toast('Error happened', {
title: 'Oh no',
variant: 'danger'
});
Run Code Online (Sandbox Code Playgroud)
这个类似服务的组合函数看起来很像这样:
// 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'
});
}; …Run Code Online (Sandbox Code Playgroud)