最近開發一個專案中遇到一個切換主題皮膚的需求,特地將開發流程整理出來供大家一起探討學習,
首先我們要先現在src檔案下的style里撰寫專案需求的scss檔案,這個程序相當惡心,而且專案經理給了幾套顏色就得寫幾套,個人建議紙style里面建一個新的檔案夾存放你寫的樣式,
值得注意的是撰寫scss檔案的時候我們得在所以的css樣式外層寫一個class選擇器將所有的樣式包裹其中,

如圖所示,
.theme-bule{ }
.theme-bule{}將所有的樣式都包裹其中的,這一步很重要,這個名字也不要亂取,要做到見名知其意,然后專案需要的其他主題顏色也用相同的方式寫好,接著在這個樣式檔案夾里建一個(index.scss)檔案將所以樣式引出,

接著在style檔案夾下找到一個一個(index.scss)的檔案[ps:這里的index.scss檔案和你建的那個主題顏色檔案夾下的index.scss檔案是不一樣的哈],這個index.scss檔案是element-admin框架自帶的,目的是將所有樣式引入到(main.js)檔案里面全域生效的,接下來我們需要在utils檔案里面封裝一個設定主題的方法,很簡單,就說給頁面body起動態class名字的,剛剛我在主題顏色css樣式最外面包裹的那個class就會動態替換以達到換皮膚的效果,

有了這一步完全還是不夠的,為了讓主題顏色能夠保存不變,我選擇了存盤在localStorage,為此我特地封裝了一個設定localStorage方法和獲取localStorage方法
/**
* 存盤localStorage
*/
export const setStore = (params = {}) => {
let {
name,
content,
type,
} = params;
name = keyName + name
let obj = {
dataType: typeof (content),
content: content,
type: type,
datetime: new Date().getTime()
}
if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
else window.localStorage.setItem(name, JSON.stringify(obj));
}
/**
* 獲取localStorage
*/
export const getStore = (params = {}) => {
let {
name,
debug
} = params;
name = keyName + name
let obj = {},
content;
obj = window.sessionStorage.getItem(name);
if (validatenull(obj)) obj = window.localStorage.getItem(name);
if (validatenull(obj)) return;
try {
obj = JSON.parse(obj);
} catch{
return obj;
}
if (debug) {
return obj;
}
if (obj.dataType == 'string') {
content = obj.content;
} else if (obj.dataType == 'number') {
content = Number(obj.content);
} else if (obj.dataType == 'boolean') {
content = eval(obj.content);
} else if (obj.dataType == 'object') {
content = obj.content;
}
return content;
}
還有我考慮到如果因為某些原因導致選擇的某個顏色無法正常使用,我得讓他有個默認顏色,因此我使用到vuex,我在store檔案夾下建了一個common.js檔案存放,

這個檔案就將我剛剛封裝的設定localStorage方法和獲取localStorage方法引入
themeName: getStore({ name: 'themeName' }) || 'theme-bule',
||運算子后面的theme-bule就是默認顏色,接下來我們在來到更改主題的頁面,


引入設定主題方法和vuex

js代碼

OK了,就可以去頁面試試效果



效果相當nice,值得注意的是在撰寫css樣式的時候可能會遇到很多樣式設定了沒效果,不妨試試秘密武器,
color:#262d37 !important;
沒錯,就是這個‘!important’,效果杠杠的,專制疑難樣式,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/226246.html
標籤:其他
上一篇:觀察者模式的彈幕案例
下一篇:Vue實作購物小球拋物線
