vue#unref TypeScript Examples

The following examples show how to use vue#unref. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From hexon with GNU General Public License v3.0 7 votes vote down vote up
function useInit(elRef: Ref<HTMLElement | null>, rect: Ref<IRect>) {
  watch(
    () => unref(elRef),
    (el) => {
      if (!el) return
      rect.value = getRect(el)
    },
    { immediate: true }
  )
}
Example #2
Source File: utils.ts    From hexon with GNU General Public License v3.0 7 votes vote down vote up
function useResize(elRef: Ref<HTMLElement | null>, rect: Ref<IRect>) {
  const removeEventListenerFnMap: Map<() => void, () => void> = new Map()
  const removeAllEventListener = () => {
    for (const [, fn] of removeEventListenerFnMap) {
      fn()
    }
    removeEventListenerFnMap.clear()
  }
  watch(
    () => unref(elRef.value),
    (el) => {
      removeAllEventListener()
      if (!el) return
      const resiableNodesSet: Set<Element | Document> = new Set()
      let cursor: Element | Document | null = el
      while (true) {
        cursor = getScrollParent(cursor)
        if (cursor === null) break
        resiableNodesSet.add(cursor)
      }
      for (const node of [...resiableNodesSet, window]) {
        const onResize = () => {
          if (!elRef.value) return
          rect.value = getRect(elRef.value)
        }
        node.addEventListener("resize", onResize)
        removeEventListenerFnMap.set(onResize, () => {
          node.removeEventListener("resize", onResize)
        })
      }
    },
    {
      immediate: true,
    }
  )
  onBeforeUnmount(() => {
    removeAllEventListener()
  })
}
Example #3
Source File: index.ts    From vue-request with MIT License 6 votes vote down vote up
unRefObject = <T extends RefObject>(val: T) => {
  const obj = {};

  Object.keys(val).forEach(key => {
    obj[key] = unref(val[key]);
  });

  return obj as {
    [K in keyof T]: UnRef<T[K]>;
  };
}
Example #4
Source File: useTitle.ts    From vite-vue3-ts with MIT License 6 votes vote down vote up
/**
 * Listening to page changes and dynamically changing site titles
 */
export function useTitle() {
  const { currentRoute } = useRouter();

  const pageTitle = usePageTitle();

  watch(
    [() => currentRoute.value.path],
    () => {
      const route = unref(currentRoute);

      const tTitle = route?.meta?.title as string;
      pageTitle.value = tTitle;
    },
    { immediate: true },
  );
}
Example #5
Source File: index.ts    From vite-vue3-ts with MIT License 6 votes vote down vote up
// dynamic use hook props
export function getDynamicProps<T, U>(props: T): Partial<U> {
  const ret: Recordable = {};

  Object.keys(props).map((key) => {
    ret[key] = unref((props as Recordable)[key]);
  });

  return ret as Partial<U>;
}
Example #6
Source File: style.ts    From fect with MIT License 6 votes vote down vote up
getHighlightRect = (elRef: MaybeElement, container: MaybeElement) => {
  const elRect = getDomRect(elRef)
  const { top: offsetTop, left: offsetLeft } = getDomRect(container)
  const containerEl = unref(container)!
  return {
    ...elRect,
    width: elRect.width || elRect.right - elRect.left,
    height: elRect.height || elRect.top - elRect.bottom,
    top: elRect.bottom + containerEl.scrollTop - offsetTop,
    left: elRect.left + containerEl.scrollLeft - offsetLeft,
    elementTop: elRect.top + containerEl.scrollTop - offsetTop
  }
}
Example #7
Source File: auto-height.ts    From fect with MIT License 6 votes vote down vote up
getTextareaAutoHeight = (el: ElementRef) => {
  const elSnapshot = unref(el)! as HTMLTextAreaElement
  const node = createNode(HIDDEN_TEXTARE_NAME, 'textarea') as HTMLTextAreaElement
  const { padding, styleContext } = getNodeStyleAttrs(elSnapshot)
  node.setAttribute('style', `${styleContext};${HIDDEN_STYLE}`)
  node.value = elSnapshot.value || elSnapshot.placeholder || ''
  const hiddenHeight = node.scrollHeight + padding
  node.value = ''
  return {
    node,
    height: addUnit(hiddenHeight)
  }
}
Example #8
Source File: create-portal.ts    From fect with MIT License 6 votes vote down vote up
createPortal = <T>(children: Component, container?: ElementRef) => {
  const elSnapshot = unref(container) || document.createElement('div')
  const app = createApp(children)
  document.body.appendChild(elSnapshot)
  const instance = app.mount(elSnapshot) as ComponentInstance<T>
  return {
    instance
  }
}
Example #9
Source File: use-click-away.ts    From fect with MIT License 6 votes vote down vote up
useClickAway = (
  listener: EventListener,
  target: Element | Ref<Element | undefined>,
  options = defaultOptions
) => {
  if (!isBrowser()) return

  const onClick = (evt: Event) => {
    const element = unref(target)
    if (element && !element.contains(evt.target as Node)) {
      listener(evt)
    }
  }
  useEventListener(options.event!, onClick, { target: document })
}
Example #10
Source File: use-event-listener.ts    From fect with MIT License 6 votes vote down vote up
useEventListener = (
  event: EventTypes,
  listener: EventListenerOrEventListenerObject,
  options: Options = {}
) => {
  const { target = window, ...rest } = options

  const remove = (el: Options['target']) => {
    const _el = unref(el)
    _el && _el.removeEventListener(event, listener, rest)
  }

  const add = (el: Options['target']) => {
    const _el = unref(el)
    _el && _el.addEventListener(event, listener, rest)
  }

  watch(
    () => unref(target),
    (el, prevEl) => {
      remove(prevEl)
      add(el)
    }
  )

  onMounted(() => add(target))
  onDeactivated(() => remove(target))
  onBeforeUnmount(() => remove(target))
}
Example #11
Source File: useEventListener.ts    From vite-vue3-ts with MIT License 5 votes vote down vote up
export function useEventListener({
  el = window,
  name,
  listener,
  options,
  autoRemove = true,
  isDebounce = true,
  wait = 80,
}: UseEventParams): { removeEvent: RemoveEventFn } {
  /* eslint-disable-next-line */
  let remove: RemoveEventFn = () => {};
  const isAddRef = ref(false);

  if (el) {
    const element = ref(el as Element) as Ref<Element>;

    const handler = isDebounce ? useDebounceFn(listener, wait) : useThrottleFn(listener, wait);
    const realHandler = wait ? handler : listener;
    const removeEventListener = (e: Element) => {
      isAddRef.value = true;
      e.removeEventListener(name, realHandler, options);
    };
    const addEventListener = (e: Element) => e.addEventListener(name, realHandler, options);

    const removeWatch = watch(
      element,
      (v, _ov, cleanUp) => {
        if (v) {
          !unref(isAddRef) && addEventListener(v);
          cleanUp(() => {
            autoRemove && removeEventListener(v);
          });
        }
      },
      { immediate: true },
    );

    remove = () => {
      removeEventListener(element.value);
      removeWatch();
    };
  }
  return { removeEvent: remove };
}
Example #12
Source File: dom.ts    From fect with MIT License 5 votes vote down vote up
getDomRect = (el: ElementRef): DomRect => {
  const element = unref(el)
  const browser = isBrowser()

  if (browser && element instanceof Window) return genDomRect(window.innerWidth, window.innerHeight)
  if (element && element.getBoundingClientRect) return element.getBoundingClientRect()
  return genDomRect(0, 0)
}
Example #13
Source File: dom.ts    From fect with MIT License 5 votes vote down vote up
isHidden = (el: ElementRef): boolean => {
  const element = unref(el)
  if (!element) return false
  const style = window.getComputedStyle(element)
  const hidden = style.display === 'none'
  const parentHidden = (element as HTMLElement).offsetParent === null && style.position !== 'fixed'
  return hidden || parentHidden
}
Example #14
Source File: useECharts.ts    From vite-vue3-ts with MIT License 4 votes vote down vote up
export function useECharts(
  elRef: Ref<HTMLDivElement>,
  theme: 'light' | 'dark' | 'default' = 'default',
) {
  const getDarkMode = computed(() => {
    return theme;
  });
  let chartInstance: echarts.ECharts | null = null;
  let resizeFn: Fn = resize;
  const cacheOptions = ref({}) as Ref<EChartsOption>;
  let removeResizeFn: Fn = () => {};

  resizeFn = useDebounceFn(resize, 200);

  const getOptions = computed(() => {
    return {
      backgroundColor: 'transparent',
      ...cacheOptions.value,
    } as EChartsOption;
  });

  function initCharts() {
    const el = unref(elRef);
    if (!el || !unref(el)) {
      return;
    }

    chartInstance = echarts.init(el);
    const { removeEvent } = useEventListener({
      el: window,
      name: 'resize',
      listener: resizeFn,
    });
    removeResizeFn = removeEvent;
    if (el.offsetHeight === 0) {
      useTimeoutFn(() => {
        resizeFn();
      }, 30);
    }
  }

  function setOptions(options: EChartsOption, clear = true) {
    cacheOptions.value = options;
    if (unref(elRef)?.offsetHeight === 0) {
      useTimeoutFn(() => {
        setOptions(unref(getOptions));
      }, 30);
      return;
    }
    nextTick(() => {
      useTimeoutFn(() => {
        if (!chartInstance) {
          initCharts();

          if (!chartInstance) return;
        }
        clear && chartInstance?.clear();

        chartInstance?.setOption(unref(getOptions));
      }, 30);
    });
  }

  function resize() {
    chartInstance?.resize();
  }

  watch(
    () => getDarkMode.value,
    () => {
      if (chartInstance) {
        chartInstance.dispose();
        initCharts();
        setOptions(cacheOptions.value);
      }
    },
  );

  tryOnUnmounted(() => {
    if (!chartInstance) return;
    removeResizeFn();
    chartInstance.dispose();
    chartInstance = null;
  });

  function getInstance(): echarts.ECharts | null {
    if (!chartInstance) {
      initCharts();
    }
    return chartInstance;
  }

  return {
    setOptions,
    resize,
    echarts,
    getInstance,
  };
}