定义主题颜色css文件theme.css
:root {
--text-color: #acacac;
--bg: linear-gradient(rgba(255, 255, 255, 0), rgb(249, 249, 253));
}
/* 自定义属性theme */
html[data-theme='dark'] {
--text-color: black;
--bg: linear-gradient(rgba(79, 119, 220, 0.316), rgb(249, 249, 253));
}
导入到main.ts
import { createSSRApp } from 'vue'
import App from './App.vue'
//导入主题颜色css文件
import './theme.css'
export function createApp() {
const app = createSSRApp(App)
return {
app,
}
}
创建全局主题变量useTheme.ts
import { ref, watchEffect } from 'vue'
const LOCAL_THEME_KEY = '__theme__'
const theme = ref(localStorage.getItem(LOCAL_THEME_KEY) || 'light')
watchEffect(() => {
//给body设置自定义属性theme,便于theme.css中识别不同主题颜色
document.documentElement.dataset.theme = theme.value
//设置本地缓存,便于刷新页面展示之前的主题
localStorage.setItem(LOCAL_THEME_KEY, theme.value)
})
//导出全局主题变量,便于其他组件使用该变量
export const useTheme = () => ({
theme,
})
导入useTheme.ts到组件中进行主题的切换
<template>
<view
@click="theme = theme === 'light' ? 'dark' : 'light'"
>
切换主题
</view>
</template>
<script setup lang="ts">
import { useTheme } from '@/hooks/useTheme'
const { theme } = useTheme()
</script>
在组件中通过css变量使用主题颜色
.content {
background-image: var(--bg);
}