|
| 1 | +import { hyphenate } from '@vue/shared' |
| 2 | +import { type Directive, type DirectiveBinding } from 'vue' |
| 3 | +import { createLoading } from './hooks/createLoading' |
| 4 | + |
| 5 | +const INSTANCE_KEY = Symbol('loading') |
| 6 | + |
| 7 | +const getAttributeName = (name: string) => { |
| 8 | + return `loading-${hyphenate(name)}` |
| 9 | +} |
| 10 | +/** |
| 11 | + * 定义挂着对象类型 |
| 12 | + */ |
| 13 | +export interface loading extends HTMLElement { |
| 14 | + [INSTANCE_KEY]: ReturnType<typeof createLoading> |
| 15 | +} |
| 16 | + |
| 17 | +// 获取指令传递的参数 |
| 18 | +const getProps = (el: loading, binding: DirectiveBinding<boolean>) => { |
| 19 | + const loadingText = el.getAttribute(getAttributeName('text')) |
| 20 | + const fullscreen = binding.modifiers.fullscreen |
| 21 | + return { |
| 22 | + loadingText: loadingText ?? 'loading', |
| 23 | + loading: binding.value, |
| 24 | + fullscreen |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * 自定义loading指令 |
| 30 | + */ |
| 31 | +const directive: Directive<loading, boolean> = { |
| 32 | + mounted(el, binding) { |
| 33 | + if (binding.value) { |
| 34 | + const props = getProps(el, binding) |
| 35 | + console.log(props) |
| 36 | + if (!props.fullscreen) { |
| 37 | + el.classList.add('relative') |
| 38 | + } |
| 39 | + el[INSTANCE_KEY] = createLoading(props, props.fullscreen ? document.body : el) |
| 40 | + } |
| 41 | + }, |
| 42 | + updated(el, binding) { |
| 43 | + if (binding.oldValue !== binding.value) { |
| 44 | + if (binding.value && !binding.oldValue) { |
| 45 | + const props = getProps(el, binding) |
| 46 | + if (!props.fullscreen) { |
| 47 | + el.classList.add('relative') |
| 48 | + } |
| 49 | + el[INSTANCE_KEY] = createLoading(props, props.fullscreen ? document.body : el) |
| 50 | + } else if (!binding.value && binding.oldValue) { |
| 51 | + el[INSTANCE_KEY]?.update(getProps(el, binding)) |
| 52 | + } |
| 53 | + if (binding.value) { |
| 54 | + el.classList.remove('overflow-y-auto') |
| 55 | + el.classList.add('overflow-y-hidden') |
| 56 | + } else { |
| 57 | + el.classList.remove('overflow-y-hidden') |
| 58 | + el.classList.add('overflow-y-auto') |
| 59 | + } |
| 60 | + } |
| 61 | + }, |
| 62 | + unmounted(el) { |
| 63 | + el[INSTANCE_KEY]?.destroy() |
| 64 | + } |
| 65 | +} |
| 66 | +export default directive |
0 commit comments