element-plus
Version:
> TODO: description
71 lines (70 loc) • 2.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useThemeVars = exports.useCssVar = exports.themeVarsKey = void 0;
const vue_1 = require("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]);
}
});
};
exports.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)
* }
* ```
*/
function useCssVar(vars, target) {
let stopWatchCssVar = null;
const elRef = vue_1.computed(() => { var _a; return vue_1.unref(target) || ((_a = window === null || window === void 0 ? void 0 : window.document) === null || _a === void 0 ? void 0 : _a.documentElement); });
const themeVars = exports.useThemeVars();
const customVars = Object.assign(Object.assign({}, themeVars), vue_1.unref(vars));
vue_1.provide(exports.themeVarsKey, vue_1.ref(customVars));
vue_1.onMounted(() => {
vue_1.isRef(vars)
? (stopWatchCssVar = vue_1.watch(vars, val => {
setVars(elRef.value, Object.assign(Object.assign({}, vue_1.unref(themeVars)), val));
}, {
immediate: true,
deep: true,
}))
: setVars(elRef.value, Object.assign(Object.assign({}, vue_1.unref(themeVars)), vars));
});
vue_1.onUnmounted(() => stopWatchCssVar && stopWatchCssVar());
}
exports.useCssVar = useCssVar;
const useThemeVars = () => {
const themeVars = vue_1.inject(exports.themeVarsKey, {});
return themeVars;
};
exports.useThemeVars = useThemeVars;