第一步安装插件:

npm install ---save webpack-theme-color-replacer

第二步在vue.config.js里面引入  修改配置

const BASE_URL = './'

const ThemeColorReplacer = require('webpack-theme-color-replacer')
const forElementUI = require('webpack-theme-color-replacer/forElementUI')
const configColor = require('./src/config/themeColor.js')

module.exports = {
	publicPath: process.env.NODE_ENV == "production" ? BASE_URL : "/",
	outputDir: 'project',
	// 打包时不生成.map文件
	productionSourceMap: false,
	//   lintOnSave:{ type:Boolean default:true } 问你是否使用eslint
	lintOnSave: false,
	chainWebpack: config => {
		// 自定义换肤
		config.plugin('webpack-theme-color-replacer')
			.use(ThemeColorReplacer)
			.tap(options => {
				options[0] = {
					fileName: 'css/theme-colors-[contenthash:8].css',
					matchColors: [...forElementUI.getElementUISeries(configColor.themeColor), '#7fffd4', //自定义颜色
					'#efefef',],
					changeSelector: forElementUI.changeSelector,
					isJsUgly: process.env.NODE_ENV !== 'development'
				}
				return options
			})
	},
	devServer: {
		port: 8081,

	}
}

themeColor.js里面存放的是一个主色调  themeColor.js

module.exports = {
    themeColor:"#409eff",
}

第三步:创建一个js文件 用来封装方法 

import client from 'webpack-theme-color-replacer/client'
import forElementUI from 'webpack-theme-color-replacer/forElementUI'
const appConfig = require('../config/themeColor.js')

export let curColor = appConfig.themeColor

// 动态切换主题色
export function changeThemeColor(newColor) {
    const options = {
        newColors: [...forElementUI.getElementUISeries(newColor), '#7fffd4', '#efefef'],
    }
    return client.changer.changeColor(options, Promise).then(t => {
        curColor = newColor
        localStorage.setItem('theme_color', curColor)
    });
}

export function initThemeColor() {
    const savedColor = localStorage.getItem('theme_color')
    if (savedColor) {
        curColor = savedColor
        changeThemeColor(savedColor)
    }
}

以上所有的准备工作已做好  下面就可以引入组件了,我在这里使用了element-ui的颜色组件如果需要修改element-ui的色调就需要使用forElementUI.getElementUISeries,其他的就可以直接传色值过来,另外需要注意的一点是这个插件只认16进制的色值

<template>
    <el-color-picker v-model="mainColor" size="small" @change="changeColor"></el-color-picker>
</template>

<script>
    import Vue from 'vue';
    import { ColorPicker } from 'element-ui';
    import { changeThemeColor, curColor } from '../libs/themeColorClient'

    Vue.use(ColorPicker)

    export default {
        data() {
            return {
                mainColor: curColor,
            };
        },
        methods: {
            changeColor(newColor) {
                changeThemeColor(newColor)
                    .then(t => console.log('123465'))
            }
        },
    }
</script>

我们的需求是换肤,并且在下次进入的时候要保留有之前换肤的效果,所以这时把换肤的色值记录到了localStorage里面,这就需要我们在main.js里面重新获取localStorage里面的值重新设置颜色 

import { initThemeColor } from './libs/themeColorClient'
initThemeColor()

 

Logo

前往低代码交流专区

更多推荐