UNPKG

element-plus

Version:
66 lines (65 loc) 2.16 kB
import { watch, isRef, onMounted, computed, unref, inject, onUnmounted, provide, ref, } from 'vue'; const VAR_PREFIX = '--el-'; const setVars = (target, val) => { Object.keys(val).forEach(key => { if (key.startsWith(VAR_PREFIX)) { target === null || target === void 0 ? void 0 : target.style.setProperty(key, val[key]); } else { target === null || target === void 0 ? void 0 : target.style.setProperty(VAR_PREFIX + key, val[key]); } }); }; export const themeVarsKey = 'themeVars'; /** * @param vars * @param target * @returns stopWatchHandler * @example * * If you pass a Ref vars param, it will generate a watch handler. * * In main.ts: * * ```ts * const themeVars = { * '--el-color-primary': '#f44336', * '--el-color-white': '#2196f3', * } * app.provide(themeVarsKey, themeVars) * ``` * Usually you need to use this function in the root component. * In components' steup: * * ```ts * setup() { * const themeVars = ref({ * '--el-button-default-background-color': '#f44336', * '--el-button-default-font-color': '#2196f3', * }) * useCssVar(themeVars) * } * ``` */ export function useCssVar(vars, target) { let stopWatchCssVar = null; const elRef = computed(() => { var _a; return unref(target) || ((_a = window === null || window === void 0 ? void 0 : window.document) === null || _a === void 0 ? void 0 : _a.documentElement); }); const themeVars = useThemeVars(); const customVars = Object.assign(Object.assign({}, themeVars), unref(vars)); provide(themeVarsKey, ref(customVars)); onMounted(() => { isRef(vars) ? (stopWatchCssVar = watch(vars, val => { setVars(elRef.value, Object.assign(Object.assign({}, unref(themeVars)), val)); }, { immediate: true, deep: true, })) : setVars(elRef.value, Object.assign(Object.assign({}, unref(themeVars)), vars)); }); onUnmounted(() => stopWatchCssVar && stopWatchCssVar()); } export const useThemeVars = () => { const themeVars = inject(themeVarsKey, {}); return themeVars; };