Element el-color-picker 颜色选择器的使用
设置的页面
<script setup lang="ts">
import { getThemeColor } from "../../utils/colorChange";
import { useUserStore } from "@/store/index";
import { reactive } from "vue";
import { ref } from "vue";
const userStore = useUserStore();
const drawer = ref(false);
const handleClose = () => {
drawer.value = false;
colorCdt.color = "";
};
const openDrawer = (bool: boolean) => {
drawer.value = bool;
};
const colorCdt = reactive({
predefineColors: [
"#ff4500",
"#ff8c00",
"#ffd700",
"#90ee90",
"#00ced1",
"#1e90ff",
"#c71585",
"rgba(255, 69, 0, 0.68)",
"rgb(255, 120, 0)",
"hsv(51, 100, 98)",
"hsva(120, 40, 94, 0.5)",
"hsl(181, 100%, 37%)",
"hsla(209, 100%, 56%, 0.73)",
"#c7158577",
],
color: "",
isShowWaterMark: true,
});
const changeTheme = (val: any) => {
console.log(val, "val");
document.documentElement.style.setProperty("--theme_bgColor", val); // 设置变量值
sessionStorage.setItem("theme_bgColor", val); // 缓存存一份
userStore.theme_bgColor = getThemeColor(); // vuex更新一下
};
defineExpose({ openDrawer });
</script>
<template>
<el-drawer
v-model="drawer"
title="设置"
:before-close="handleClose"
size="20%"
>
<div class="DrawItem">
<span>主题更改:</span>
<el-color-picker
@change="changeTheme"
v-model="colorCdt.color"
show-alpha
:predefine="colorCdt.predefineColors"
>
</el-color-picker>
</div>
</el-drawer>
</template>
<style lang="scss" >
.DrawItem {
box-sizing: border-box;
padding: 0 18px;
display: flex;
align-items: center;
justify-content: space-around;
justify-content: space-between;
margin-bottom: 18px;
font-size: 13px;
font-weight: 600;
}
</style>
在store里面保存一个颜色变量值
获取主题颜色的方法写在colorChange.ts
// 获取主题颜色
export function getThemeColor() {
// 有缓存用缓存,没缓存用默认
let cache_theme_bgColor = sessionStorage.getItem("theme_bgColor");
if (cache_theme_bgColor) {
document.documentElement.style.setProperty(
"--theme_bgColor",
cache_theme_bgColor
);
return cache_theme_bgColor;
} else {
let theme_bgColor = getComputedStyle(
document.documentElement
).getPropertyValue("--theme_bgColor");
return theme_bgColor;
}
}
:root定义全局样式和变量
定义 :root 后,所有变量都将被保存在 :root 中,并且可以在整个页面的任何位置使用。这使得我们可以轻松地为网站设置一些通用的变量,如颜色、字体、间距等等
reset.css【在main.ts里全局引入】
:root {
--theme_bgColor: #fff;
}
在layout获取颜色的变量值【以防一刷新颜色值丢失】
如果需要让页面背景变可以再layout 获取一次颜色值
如果需要侧边栏背景色也变,可以sidebar获取颜色变量值