UNPKG

yanzhen-design-vue

Version:

102 lines (101 loc) 3.34 kB
import { getCurrentInstance, computed, unref, camelize, mergeProps, useAttrs } from "vue"; import { isOn, hyphenate, hasOwn } from "@vue/shared"; import { isObject, isArray } from "@yanzhen-libs/utils"; import { fromPairs, upperFirst, camelCase, omit, pick } from "lodash-es"; import { toHandlerKey } from "@yanzhen-libs/utils-vue"; function isEmitListener(options, key) { if (!options || !isOn(key)) { return; } key = key.slice(2).replace(/Once$/, ""); for (const emitKey of [key[0].toLowerCase() + key.slice(1), hyphenate(key), key]) { if (hasOwn(options, emitKey)) { return emitKey; } } } const useProxy = (proxyConfig) => { const instance = getCurrentInstance(); const { props: proxyProps, on: proxyEvents, excludeProps } = proxyConfig || {}; return computed(() => { const bindProps = Object.assign({}, instance.attrs); if (proxyProps) { Object.keys(proxyProps).forEach((propKey) => { if (proxyProps[propKey]) { bindProps[propKey] = unref(proxyProps[propKey]); } }); } const rawProps = instance.vnode.props; if (rawProps) { Object.keys(rawProps).forEach((propKey) => { const matchKey = isEmitListener(instance.emitsOptions, propKey); if (matchKey) { bindProps[propKey] = (proxyEvents == null ? void 0 : proxyEvents[camelize(matchKey)]) || rawProps[propKey]; } }); } Object.keys(instance.props).forEach((propKey) => { if (!(propKey in (proxyProps ?? {})) && !(excludeProps == null ? void 0 : excludeProps.includes(propKey))) { bindProps[propKey] = instance.props[propKey]; } }); return bindProps; }); }; function useProxyConfig(props, emits, context) { const _emits = computed(() => { const _emitsObj = unref(emits); let keys = []; if (isObject(_emitsObj)) { keys = Object.keys(_emitsObj); } else if (isArray(_emitsObj)) { keys = _emitsObj.filter((value) => typeof value === "string"); } const _props = unref(props); const funs = fromPairs( Object.entries(_props).map(([k, value]) => { if (k.startsWith("on")) { const eventName = toHandlerKey(k); return [eventName, value]; } return [k, value]; }) ); return fromPairs( keys.map((key) => { const emit = context == null ? void 0 : context.emit; const k = key.startsWith("on") ? key : `on${upperFirst(camelCase(key))}`; const eventName = toHandlerKey(key); return [ eventName, (...args) => { if (typeof funs[eventName] === "function") { funs[eventName](...args); } else if (typeof funs[k] === "function") { funs[k](...args); } else if (typeof emit === "function") { emit(key, ...args); } } ]; }) ); }); return computed(() => { let _props = unref(props); const exclude = context == null ? void 0 : context.exclude; const include = context == null ? void 0 : context.include; if (exclude) { _props = omit(_props, ...exclude); } if (include) { _props = pick(_props, ...include); } return mergeProps(useAttrs(), _props, unref(_emits)); }); } export { useProxy, useProxyConfig };