0.0.4 • Published 1 year ago
@xiaohaih/create-api v0.0.4
create-api
- 可通过
api方式调用
- 可将
vue组件挂载到全局实例上供全局调用- 通过
useComponent函数调用vue组件
安装
基于
npm
pnpmpnpm i -S @xiaohaih/create-api
npmnpm install @xiaohaih/create-api
yarnyarn add @xiaohaih/create-api基于
cdn<script src="https://unpkg.com/@xiaohaih/create-api/dist/index.umd.cjs"></script>
使用 - 通过函数调用
<script lang="ts" setup>
import { useComponent } from '@xiaohaih/create-api';
const dialogComponent = useComponent(HDialog);
function clickHandle() {
    dialogComponent({
        title: '显示弹窗',
    }).show();
}
</script>使用 - 挂载到 vue 实例上
main.ts
import { createApp } from 'vue';
import { install } from '@xiaohaih/create-api';
const app = createApp(App);
app.use(install);
a.vue
import { create } from '@xiaohaih/create-api';
import Dialog from './components/dialog.vue';
// 直接挂载弹窗
create(Dialog);
// 或者通过实例挂载弹窗
// getCurrentInstance()?.proxy?.$create(Lump);
// 在 js 中调用, 默认不具备响应式
// 如要支持响应式, props 应为 ref 或 reactive
Dialog.$create({
    title: 'test',
    content: '内容',
}).show();
// 在 vue 组件中可以通过 getCurrentInstance 调用
getCurrentInstance()?.proxy?.$createDialog({
    title: 'test',
    content: '内容',
}).show();
src/types/create.d.ts
// 为全局组件补充声明
import type { CreateFn } from '@xiaohaih/create-api';
import type Dialog from '@/components/dialog.vue';
declare module 'vue' {
    interface ComponentCustomProperties {
        $createDialog: CreateFn<typeof Dialog>;
    }
}为 typescript 补充声明
tips: 因全局上补充了属性, 且直接暴露的源文件, 故需加上如下代码
# tsconfig.json
{
    "compilerOptions": {
        "types": ["@xiaohaih/create-api/global"]
    }
}导出的函数
install(vueApp, [options]) 全局安装方法
- 参数:
- {Vue} vueApp 全局实例
- {object}
options可选配置项- {boolean}
options.single是否作为当前上下文中的单例, 默认true- {boolean}
options.global是否将组件挂载到根实例上- {boolean}
options.mergeProps重复调用时是否与上次调用时传的props进行合并- {string | Element | (() => Element)}
options.appendTo挂载到的节点, 默认document.body- tips:
- 会为全局数据上增加
$create方法,$create等同下方的create
useComponent 通过 js 方式挂载组件
- 参数
- {VueComponent}
component需要挂载的组件- {object | VueInstance}
options|instance传递的配置项(与 install 第二个参数相同), 无配置项时可传第三个参数- {VueInstance}
instance挂载时绑定到的实例- 返回值
- {(
props: 传给组件的参数,children: 插槽或子级) =>CustomComponent} 调用useComponent后的返回值
CustomComponent是component的实例, 在实例上增加了四个方法👇
- {() =>
CustomComponent}show显示组件(需内部实现show方法)- {() =>
CustomComponent}hide隐藏组件(需内部实现hide方法)- {() => void}
$unmount卸载组件- {(
props: object | null,mergeProps?: boolean) =>CustomComponent}$updateProps手动更新参数- {(children?: VNodeChildren | null) =>
CustomComponent}$updateSlots主动更新插槽- {() =>
CustomComponent}$forceUpdate强制更新组件