引申:
网上的方式大多是通过在静态文件夹下存放两套CSS,
在index.html里,
动态写入 link标签,
动态切换CSS,
这种方法理论来说可行,但是可能存在样式覆盖问题,
后来尝试后不可行,于是把主意打到了main.js里面
const styleDefine = localStorage.get('GLOBAL_THEME')//缓存的变量
let loadStyle
async function importCss() {
if (styleDefine === 'dark') {
loadStyle = await import('./assets/XXXX1.css')
} else {
loadStyle = await import('./assets/XXXX2.css')
}
return loadStyle
}
importCss()
这种方法通过你的缓存来切换主题,但是主题是切换了,但是需要手动刷新一下,
综上所述 :
触发:
changeCss(event) {
if (event === '1') {
this.$store.dispatch('setThemeFun', 'dark')
localStorage.set(GLOBAL_THEME, 'dark')
} else {
this.$store.dispatch('setThemeFun', 'light')
localStorage.set(GLOBAL_THEME, 'light')
}
}
Vuex:
changeGlobalTheme: (state, value) => {
state.GlobalTheme = value
if (storage.get(GLOBAL_THEME) !== value) {
window.location.reload() //手动刷新才能生效
}
localStorage.set(GLOBAL_THEME, value)
state.theme = value
}
main.js
const styleDefine = localStorage.get('GLOBAL_THEME')//缓存的变量
let loadStyle
async function importCss() {
if (styleDefine === 'dark') {
loadStyle = await import('./assets/XXXX1.css')
} else {
loadStyle = await import('./assets/XXXX2.css')
}
return loadStyle
}
importCss()