17.vue 自定义主题
1.安装需要的相关依赖
npm i element-theme -g
npm i element-theme-chalk -D
2.初始化变量文件
et -i
项目根目录下生成
打卡此文件
修改变量
编译主题
et
3.引入主题
在main.js
中引入
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 导入字体图标库
import './assets/fonts/iconfont.css'
import './plugins/element.js'
import 'element-ui/lib/theme-chalk/index.css'
import '../theme/index.css'
import ElementUI from 'element-ui'
// 导入全局样式表
import './assets/scss/global.scss'
// 导入全局接口入口文件
import api from './api/index'
// 导入国际化i18n
import VueI18n from 'vue-i18n'
// 导入全局mock
import './mock'
Vue.config.productionTip = false
Vue.use(VueI18n) // 通过插件的形式挂载
Vue.use(ElementUI)
const i18n = new VueI18n({
locale: 'zh-CN', // 语言标识
// this.$i18n.locale // 通过切换locale的值来实现语言切换
messages: {
'zh-CN': require('./assets/lang/zh'), // 中文语言包
'en-US': require('./assets/lang/en') // 英文语言包
}
})
// 将导入的接口文件全局挂载在vue全局上
Vue.prototype.$api = api
new Vue({
i18n,
router,
store,
render: h => h(App)
}).$mount('#app')
4.封装动态换肤色ThemePicker.vue组件
参考大神:
博客园:https://www.cnblogs.com/dengqichang/p/10364455.html
大神的博客地址
- ThemePicker.vue内容
<template>
<el-color-picker class="theme-picker" popper-class="theme-picker-dropdown" v-model="theme" :size="size"> </el-color-picker>
</template>
<script>
const version = require('element-ui/package.json').version // element-ui version from node_modules
const ORIGINAL_THEME = '#409EFF' // default color
export default {
name: 'ThemePicker',
props: {
default: {
// 初始化主题,可由外部传入
type: String,
// default: '#EB815B'
default: '' + localStorage.getItem('tremePackers') + ''
},
size: {
// 初始化主题,可由外部传入
type: String,
default: 'small'
}
},
data() {
return {
chalk: '', // content of theme-chalk css
theme: ORIGINAL_THEME,
showSuccess: true // 是否弹出换肤成功消息
}
},
mounted() {
if (this.default != null) {
this.theme = this.default
this.$emit('onThemeChange', this.theme)
this.showSuccess = false
}
},
watch: {
theme(val, oldVal) {
if (typeof val !== 'string') return
const themeCluster = this.getThemeCluster(val.replace('#', ''))
const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
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
}
}
const chalkHandler = getHandler('chalk', 'chalk-style')
if (!this.chalk) {
const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
this.getCSSString(url, chalkHandler, 'chalk&#