通过css属性实现可变化的全局样式变量


// 代理访问和设置
const options = {
  // 主题色
  themeColor: 'red',
  // 文本主颜色
  textColor: '#333',
  // h1 h2 h3 h4 h5
  h1: '1.6rem',
  h2: '1.4rem',
  h3: '1.2rem',
  h4: '1rem',
  h5: '0.8rem'
};

const policy = {
  themeColor: '--theme-color',
  textColor: '--text-color',
  h1: '--h-1',
  h2: '--h-2',
  h3: '--h-3',
  h4: '--h-4',
  h5: '--h-5',
};

let canChange = false;
function setGlobalProperty (type: string, val: string): string {
  document.body.style.setProperty(policy[type], val);
  canChange = true;
  options[type] = val;
  canChange = false;
  return val;
}

Reflect.ownKeys(options).forEach((key: any) => {
  setGlobalProperty(key, options[key]);
  reactive(options, key, options[key])
});

function reactive (options, key, value) {
 Reflect.defineProperty(options, key, {
    get () {
      return value;
    },
    set (val) {
      if (canChange) value = val;
      else console.error('please use useGlobal return array[1] to reset state')
    }
  })
}

export default function useGlobal () {
  return [options, setGlobalProperty]
}
原文地址:https://www.cnblogs.com/smallZoro/p/14029962.html