ux.*_*eer 8 typescript vue.js bootstrap-vue vuejs3 vue-composition-api
我想创建一个用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'
});
这个类似服务的组合函数看起来很像这样:
// 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 {};
  }
});
ux.*_*eer 10
好吧,我很快在同一个 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 社区!
还有:
import { getCurrentInstance } from 'vue'  // or from '@vue/composition-api'
这root将从该方法中获取调用组件的上下文。
const root = getCurrentInstance();  // same as ctx.root in component
| 归档时间: | 
 | 
| 查看次数: | 5318 次 | 
| 最近记录: |