vite@5.4.10
@arco-design/web-vue@2.56.3
打包工具更改变量值
想通过打包工具替换样式变量, 发现按照官网写了都没有生效。(其实是看漏了说明)
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import config from './config'
const { port } = config
import path from 'path'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
host: '0.0.0.0',
port
},
css: {
preprocessorOptions: {
less: {
modifyVars: {
'arcoblue-6': '#ff0000' // 对应的变量在node_model里,官方有说明
},
javascriptEnabled: true,
}
}
},
resolve: {
alias: {
'@src': path.resolve(__dirname, './src')
}
}
})
必须先引用样式, 可以在一个less文件里引入官方的less文件(官方-定制主题)有说明
// main.ts
...
import '@arco-design/web-vue/dist/arco.less' // 需要引入才能在打包的时候更改变量
....
使用变量( 变量用于改变原来组件的样式 )
// xxx.vue
<style scoped lang="less">
.abc {
background: rgb(var(--arcoblue-6))
}
</style>
用颜色选择器更新主题色
<a-tooltip content="更改主题色">
<a-color-picker v-model="color" size="mini" @change="handlerEditTheme">
<a-button
class="nav-btn"
type="outline"
shape="circle"
>
<template #icon>
<icon-bulb />
</template>
</a-button>
</a-color-picker>
</a-tooltip>
我的写在右上角导航条里,所以有别的标签包括,正常只需要一个颜色选择器,看着官网的方法监听change变化,拿到change的颜色值
官方小伙伴给出的方法, 注意这里要安装vueuse hook方法
import { useDebounceFn } from '@vueuse/core';
import { generate, getRgbStr } from '@arco-design/color';
/**
* 切换主题色
*/
export default function useColorTheme() {
const createStyleString = (color, dark?: boolean) => {
const hexList = generate(color, { list: true, dark })
return hexList
.map((hex, i) => {
const rgb = getRgbStr(hex);
return `--primary-${i + 1}: ${rgb}; --arcoblue-${i + 1}: ${rgb};`
})
.join('')
};
/**
* 更新主题色
* @param color 主题色
*/
const updateThemeColor = useDebounceFn(color => {
const style = createStyleString(color)
const darkStyle = createStyleString(color, true)
const customStyle = `
body{${style}}
body[arco-theme='dark'] {${darkStyle}}
`
injectStyle(customStyle)
}, 10)
/**
* 注入样式
* @param styleText 样式字符串
*/
const injectStyle = (styleText: string) => {
const oldStyle = document.getElementById('theme-color')
if (oldStyle) {
oldStyle.innerHTML = styleText
} else {
const style = document.createElement('style')
style.id = 'theme-color'
style.innerHTML = styleText
document.head.appendChild(style)
}
};
return {
injectStyle,
updateThemeColor
};
}
// xxx.vue
...
// 引入js方法
import updateTheme from '@src/utils/theme.ts'
const { updateThemeColor } = updateTheme()
const color = ref('#165DFF')
// 颜色选择器的监听事件
const handlerEditTheme = () => {
updateThemeColor(color.value)
}
有更好的方法欢迎留言讨论~