vite+vue+ts+element-plus从零开发管理后台框架(17)-主颜色动态设置

之前的主颜色是静态设置的,这里通过颜色选择器选择颜色动态设置。

删除静态设置主颜色

编辑src/style.css,删除如下静态主颜色样式。

:root {
  --el-color-primary: red;
}

:root.dark {
  --el-color-primary: red;
}

颜色 Store

新建src/store/color.ts,内容如下。主要是有一个primary主颜色的属性并且默认是element-plus的主颜色,持久化数据,预定义了7个颜色,primaryChange是颜色选择器实时改变更新网页属性的回调,primarySave是颜色选择器确定颜色时的回调。

import { defineStore } from 'pinia'


const useColorStore = defineStore('appcolor', {
    state: () => {
        const primary = '#409eff'

        return {
            primary,
        }
    },

    persist: true,

    getters: {
        primaryPredefines(): string[] {
            return ['#FF0000 ', '#FF7F00', '#FFFF00 ', '#00FF00 ', '#00FFFF ', '#0000FF', '#8B00FF']
        }
    },

    actions: {
        primaryChange(val: string | null) {
            if (!val) return

            const el = document.documentElement
            el.style.setProperty('--el-color-primary', val)
        },

        primarySave(val: string | null) {
            if (!val) return

            this.primary = val
        }
    }
})


export default useColorStore

使用 Store

编辑src/views/Main.vue,导入并实例化颜色Store

import useMenuStore from '@/store/menu'
import useColorStore from '@/store/color'
const menuStore = useMenuStore()
const colorStore = useColorStore()

templateheader-right下最前面添加如下代码


预览和设置主颜色

vite+vue+ts+element-plus从零开发管理后台框架(17)-主颜色动态设置_第1张图片

这样就达到了颜色选择器改变颜色的同时改变网页主颜色,并且只有点击了OK按钮才会最终应用这个主颜色,如果点击了空白区域关闭颜色选择器就会退回到之前的主颜色。

初始化主颜色

虽然已经能动态设置主颜色了,但当我们刷新浏览器后显示的主颜色跟最后设置的主颜色不一样,原因是网页重新加载后没有初始化主颜色。

vite+vue+ts+element-plus从零开发管理后台框架(17)-主颜色动态设置_第2张图片

编辑src/App.vue,导入和初始化主颜色。

import { useDark } from '@vueuse/core'

import useColorStore from '@/store/color'


useDark()

const colorStore = useColorStore()
colorStore.primaryChange(colorStore.primary)

再设置主颜色并刷新浏览器,发现主颜色已经初始化了。

你可能感兴趣的:(vue.js)