element、vant已经成功实现
demo:我给ws写了个轮询测试
主要是看了element-admin实现的切换皮肤,刚好有个手机端有这种需求,除了是后端传入,看了下,还真能实现
主要思路就是通过less或sass 修改默认颜色 例如vant的默认颜色是@white,通过export导出存入vuex,修改vuex触发事件请求云端的同版本css,然后正则将默认颜色改成配置好的颜色,放入head的style中,这是element的思路,真的太骚了。
具体实现(vant):
1.首先我的ws,随便写的
const WebSocket = require('ws')
const wss = new WebSocket.Server(
{
port: 8082,
host: '127.0.0.1',
backlog: 50,
maxPayload: 66
},
() => {
console.log('创建服务器')
}
)
const color = ['#dddddd', '#ffffff', '#eeeeee', '#1890ff']
let i = -1
wss.on('connection', (ws, req) => {
setInterval(() => {
if (i >= color.length) {
i = -1
}
ws.send(color[i])
i++
}, 3000)
})
2.我去除了main.js、vue.config.js、babel.config.js、.babelrc中的所有vant的css引用与懒加载,手动去引用css,其中babel.config.js、.babelrc我去除了style配置,其他几个删除了@import ‘vant/lib/index.less’
3.新建css文件,我是在public中建立的,在哪里看自己喜好
// vant是@white element是@--color-primary
// 本地默认颜色我同步了vant白色 element是蓝色
// export将变量抛出
// 接收vant的样式文件 并修改默认颜色 这个文件记得在main.js引入
@import '~vant/lib/index.less';
@white: #fff;
:export {
theme: @white;
}
4.vuex接收变量 创建settings模块
// 这里主要是主题颜色的异步修改
import variables from '../../../public/element-variables.less'
export default{
state:{
theme: variables.theme,
},
mutations:{
CHANGE_SETTING: (state, { key, value }) => {
// eslint-disable-next-line no-prototype-builtins
if (state.hasOwnProperty(key)) {
state[key] = value
}
}
},
actions:{
changeSetting({ commit }, data) {
commit('CHANGE_SETTING', data)
}
}
}
5.创建组件ThemePicker用于监听颜色变化,计算颜色并修改头部style
<template>
// 这里我使用了el-color-picker这个组件,主要是为了测试颜色变更是否生效,其实这个组件并不重要,有需要的可以npm i 一下 整体代码直接拿的element中得组件
<el-color-picker
v-model="theme"
:predefine="[
'#409EFF',
'#1890ff',
'#304156',
'#212121',
'#11a983',
'#13c2c2',
'#6959CD',
'#f5222d'
]"
class="theme-picker"
popper-class="theme-picker-dropdown"
/>
</template>
<script>
// 这里定义版本号 如果是element修改vant为element-ui
const version = require('vant/package.json').version // vant version from node_modules
// 默认颜色是有坑的,vant白色,element蓝色,记得这里要用线上的颜色,正则就是匹配这个颜色替换成传入的颜色
// 大概逻辑就是将你传入的颜色转成多种格式 去正则匹配默认颜色 替换请求的线上的css的默认颜色 并添加到头部
// 可以将el-color-picker改成div 然后在app中注册 我只是为了可视化
const ORIGINAL_THEME = '#fff' // default color
import elColorPicker from 'el-color-picker'
export default {
data() {
return {
chalk: '', // content of theme-chalk css
theme: ''
}
},
components:{elColorPicker},
computed: {
defaultTheme() {
return this.$store.state.setting.theme
}
},
watch: {
defaultTheme: {
handler: function(val, oldVal) {
this.theme = val
},
immediate: true
},
async theme(val) {
const oldVal = this.chalk ? this.theme : ORIGINAL_THEME
if (typeof val !== 'string') return
const themeCluster = this.getThemeCluster(val.replace('#', ''))
console.log(oldVal);
const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
// const $message = this.$message({
// message: ' Compiling the theme',
// customClass: 'theme-message',
// type: 'success',
// duration: 0,
// iconClass: 'el-icon-loading'
// })
const getHandler = (variable, id) => {
return () => {
const originalCluster = this.getThemeCluster(
ORIGINAL_THEME.replace('#', '')
)
const newStyle = this.updateStyle(
this[variable],
originalCluster,
themeCluster
)
let styleTag = document.getElementById(id)
if (!styleTag) {
styleTag = document.createElement('style')
styleTag.setAttribute('id', id)
document.head.appendChild(styleTag)
}
styleTag.innerText = newStyle
}
}
if (!this.chalk) {
// vant是这个路径,element不是 记得改掉,不知道的话去看原来css引入的路径
const url = `https://unpkg.com/vant@${version}/lib/index.css`
await this.getCSSString(url, 'chalk')
}
const chalkHandler = getHandler('chalk', 'chalk-style')
chalkHandler()
const styles = [].slice
.call(document.querySelectorAll('style'))
.filter((style) => {
const text = style.innerText
return (
new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
)
})
styles.forEach((style) => {
const { innerText } = style
if (typeof innerText !== 'string') return
style.innerText = this.updateStyle(
innerText,
originalCluster,
themeCluster
)
})
this.$emit('change', val)
// $message.close()
}
},
created() {
this.localSocket()
},
methods: {
updateStyle(style, oldCluster, newCluster) {
console.log(oldCluster, newCluster);
let newStyle = style
// 这里颜色切换我加了动画 就是让用户如果在线,切换效果不死板
oldCluster.forEach((color, index) => {
newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index]+';transition: color 2s linear;transition: background-color 2s linear;')
})
// console.log(newStyle);
return newStyle
},
getCSSString(url, variable) {
return new Promise((resolve) => {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '')
resolve()
}
}
xhr.open('GET', url)
xhr.send()
})
},
localSocket() {
const that = this
if ('WebSocket' in window) {
// console.log("您的浏览器支持 WebSocket!");
// location.host
that.ws = new WebSocket('ws://' + '127.0.0.1:8081')
that.ws.onopen = function() {
console.log('websocket连接成功')
}
that.ws.onmessage = function(res) {
if (typeof res.data != 'string') return
that.theme = res.data
console.log('收到服务器内容', res.data)
}
that.ws.onclose = function() {
// 关闭 websocket
console.log('连接已关闭...')
// 断线重新连接
setTimeout(() => {
that.localSocket()
}, 2000)
}
} else {
// 浏览器不支持 WebSocket
console.log('您的浏览器不支持 WebSocket!')
this.openNotificationWithIcon(
'error',
'浏览器',
'您的浏览器不支持显示消息请更换',
1,
1
)
}
},
getThemeCluster(theme) {
const tintColor = (color, tint) => {
let red = parseInt(color.slice(0, 2), 16)
let green = parseInt(color.slice(2, 4), 16)
let blue = parseInt(color.slice(4, 6), 16)
if (tint === 0) {
// when primary color is in its rgb space
return [red, green, blue].join(',')
} else {
red += Math.round(tint * (255 - red))
green += Math.round(tint * (255 - green))
blue += Math.round(tint * (255 - blue))
red = red.toString(16)
green = green.toString(16)
blue = blue.toString(16)
return `#${red}${green}${blue}`
}
}
const shadeColor = (color, shade) => {
let red = parseInt(color.slice(0, 2), 16)
let green = parseInt(color.slice(2, 4), 16)
let blue = parseInt(color.slice(4, 6), 16)
red = Math.round((1 - shade) * red)
green = Math.round((1 - shade) * green)
blue = Math.round((1 - shade) * blue)
red = red.toString(16)
green = green.toString(16)
blue = blue.toString(16)
return `#${red}${green}${blue}`
}
const clusters = [theme]
for (let i = 0; i <= 9; i++) {
clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
}
clusters.push(shadeColor(theme, 0.1))
return clusters
}
}
}
</script>
<style>
.theme-message,
.theme-picker-dropdown {
z-index: 99999 !important;
}
.theme-picker .el-color-picker__trigger {
height: 26px !important;
width: 26px !important;
padding: 2px;
}
.theme-picker-dropdown .el-color-dropdown__link-btn {
display: none;
}
</style>
6.大功告成
7.后来想着好多图标用的图片咋办,想了想好像svg可以,感觉也可以实现,转svg后切换颜色
原文:https://blog.stride.fun/blogs/category1/2022/22413.html