feature(tooltip): add tooltip directive

This commit is contained in:
Sagi 2022-10-12 15:56:08 +08:00
parent 6b4b1f2e57
commit 025ca668dc
5 changed files with 57 additions and 3 deletions

View File

@ -1,12 +1,14 @@
import type { App } from 'vue';
import Tooltip from './src/tooltip.component';
import TooltipDirective from './src/tooltip.directive';
export * from './src/tooltip.props';
export { Tooltip };
export { Tooltip, TooltipDirective };
export default {
install(app: App): void {
app.component(Tooltip.name, Tooltip);
app.directive('tooltip', TooltipDirective);
}
};

View File

@ -0,0 +1,45 @@
import { App, createApp, onUnmounted, reactive } from "vue";
import { TooltipProps } from "./tooltip.props";
import Tooltip from "./tooltip.component";
function initInstance(props: TooltipProps, content?: string): App {
const container = document.createElement('div');
const app: App = createApp({
setup() {
onUnmounted(() => {
document.body.removeChild(container);
});
return () => <Tooltip {...props} onClose={app.unmount}></Tooltip>;
}
});
document.body.appendChild(container);
app.mount(container);
return app;
}
function showTooltip(options: TooltipProps): void {
const props: TooltipProps = reactive({
...options
});
initInstance(props);
}
const tooltipDirective = {
mounted: (element: HTMLElement, binding: Record<string, any>, vnode: any) => {
element.addEventListener('mouseenter', ($event: MouseEvent) => {
$event.stopPropagation();
showTooltip({
content: 'This is a tooltip',
width: 100,
customClass: '',
position: 'top',
referenceBoundingRect: element.getBoundingClientRect()
});
});
element.addEventListener('mouseleave', ($event: MouseEvent) => {
$event.stopPropagation();
});
},
unMounted: (element: HTMLElement, binding: Record<string, any>, vnode: any) => { }
};
export default tooltipDirective;

View File

@ -18,6 +18,7 @@ export const tooltipProps = {
content: { type: String },
width: { type: Number },
customClass: { type: String },
position: { type: String as PropType<TooltipPosition>, default: 'top' }
position: { type: String as PropType<TooltipPosition>, default: 'top' },
referenceBoundingRect: { type: Object, default: {} }
};
export type TooltipProps = ExtractPropTypes<typeof tooltipProps>;

View File

@ -1,7 +1,10 @@
<script setup lang="ts">
import Tooltip from '../../components/tooltip/src/tooltip.component';
import Button from '../../components/button/src/button.component';
</script>
<template>
<Tooltip> </Tooltip>
<Button v-tooltip> 显示提示信息 </Button>
</template>

View File

@ -1,5 +1,8 @@
import { createApp } from 'vue';
import './style.css';
import App from './app.vue';
import Tooltip from '../components/tooltip/index';
const app = createApp(App);
app.use(Tooltip).mount('#app');
createApp(App).mount('#app');