gpt4 book ai didi

typescript - 如何从 Vue Composition API/Vue 3.0 + TypeScript 中的组合函数访问根上下文?

转载 作者:行者123 更新时间:2023-12-03 06:36:24 24 4
gpt4 key购买 nike

我要创建一个可重用的包装函数 写于 typescript 使用 触发 toast 通知合成函数 ,如 Vue 3.0 的当前规范中所定义:Composition API RFC .

本示例使用 BootstrapVue v2.0 toast 组件。使用 Vue 2,它将通过 this.$bvToast 调用。 vue组件实例注入(inject)在根上下文中 :

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 {};
}
});

最佳答案

好吧,我很快就在同一个 RFC 站点上找到了一个合适的示例。但决定在这里分享我的例子。

为了清楚起见,我认为 RFC 站点目前不包含 TypeScript 中的示例。由于这种编写 Vue 3.0 组件和组合函数的新方式(作为 Mixins 的替代品)需要一些时间来适应。

答:在将所需部分对象解构到组件代码中时,您可以将上下文对象直接传递给组合函数。

// File: @/util/notify.ts
// import { SetupContext } from '@vue/composition-api';

export function useNotify({ root }) {
const notifyError = (title: string, msg: string) => {
root.$bvToast.toast(msg, {
title,
variant: 'danger'
});
};

return { notifyError };
}

export default useNotify;
// Use in your functional component:
import { createComponent, SetupContext } from '@vue/composition-api';

import { useNotify} from '@/util/notify';

export default createComponent({
name: 'MyFailingComponent',
setup(props: any, context: SetupContext) {
const { notifyError } = useNotify(context);

notifyError('Request error', 'There was an error processing your request, please try again later.');

return {};
}
});

使用带有复杂对象解构的 TypeScript 类型也是如此 ,当将多个函数参数作为对象传递时:
// File: @/util/notify.ts
import { SetupContext } from '@vue/composition-api';

export function useNotify({ context, defaultTitle = 'Hey!' }: { context: SetupContext, defaultTitle?: string }) {
const notifyError = (msg: string, title?: string) => {
context.root.$bvToast.toast(msg, {
title: title || defaultTitle,
variant: 'danger',
});
};

return {
notifyError,
};
}

export default useNotify;

// Usage like:
const { notifyError } = useNotify({ context });
// Or
const { notifyError } = useNotify({ context, defaultTitle: 'Hey there' });

简洁的语法,干得好 Vue 社区!

关于typescript - 如何从 Vue Composition API/Vue 3.0 + TypeScript 中的组合函数访问根上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com