refactor(projects): 去除在pinia的getters的函数调用副作用,用watch代替

This commit is contained in:
Soybean
2022-04-21 00:43:17 +08:00
parent 24010d05fb
commit b35ed8960d
4 changed files with 49 additions and 19 deletions

View File

@ -1,6 +1,8 @@
import { watch, onUnmounted } from 'vue';
import { useOsTheme } from 'naive-ui';
import type { GlobalThemeOverrides } from 'naive-ui';
import { useElementSize } from '@vueuse/core';
import { kebabCase } from 'lodash-es';
import { setThemeColor } from '@/utils';
import { useThemeStore } from '../modules';
@ -11,6 +13,7 @@ export default function subscribeThemeStore() {
const { width } = useElementSize(document.documentElement);
const { addDarkClass, removeDarkClass } = handleWindicssDarkMode();
// 监听主题颜色
const stopThemeColor = watch(
() => theme.themeColor,
newValue => {
@ -19,6 +22,17 @@ export default function subscribeThemeStore() {
{ immediate: true }
);
// 监听naiveUI themeOverrides
const stopThemeOverrides = watch(
() => theme.naiveThemeOverrides,
newValue => {
if (newValue.common) {
addThemeCssVarsToHtml(newValue.common);
}
},
{ immediate: true }
);
// 监听暗黑模式
const stopDarkMode = watch(
() => theme.darkMode,
@ -55,6 +69,7 @@ export default function subscribeThemeStore() {
onUnmounted(() => {
stopThemeColor();
stopThemeOverrides();
stopDarkMode();
stopOsTheme();
stopWidth();
@ -75,3 +90,17 @@ function handleWindicssDarkMode() {
removeDarkClass
};
}
type ThemeVars = Exclude<GlobalThemeOverrides['common'], undefined>;
type ThemeVarsKeys = keyof ThemeVars;
/** 添加css vars至html */
function addThemeCssVarsToHtml(themeVars: ThemeVars) {
const keys = Object.keys(themeVars) as ThemeVarsKeys[];
const style: string[] = [];
keys.forEach(key => {
style.push(`--${kebabCase(key)}: ${themeVars[key]}`);
});
const styleStr = style.join(';');
document.documentElement.style.cssText += styleStr;
}