起因
最近因公司需求,需要實(shí)現(xiàn)主題換膚功能,不僅僅是顏色的更改,還需要包括圖片,字體等文件等更換,因此在百度里各種實(shí)現(xiàn)方案后,決定根據(jù)scss+style-loader/useable
做換膚。
項(xiàng)目開(kāi)始
首先我們用vue-element-admin
這個(gè)開(kāi)源的后臺(tái)管理系統(tǒng)項(xiàng)目來(lái)做demo演示,為了便于做二次開(kāi)發(fā),下載vue-admin-template來(lái)開(kāi)發(fā)。
// 從github下載vue-admin-templateclone https://github.com/PanJiaChen/vue-admin-template.gitcd vue-admin-templatenpm installnpm run dev
運(yùn)行成功后的效果
安裝style-loader處理器
因?yàn)?code>vue-admin-template項(xiàng)目是添加過(guò)sass-loader
依賴的,所以不用我們?cè)俅伟惭b,在上一步就已經(jīng)安裝好了。
npm install style-loader --save-dev
創(chuàng)建主題文件
在src目錄下創(chuàng)建theme-chalk、theme-light
主題文件夾
在兩個(gè)主題目錄下創(chuàng)建index.useable.scss文件 
在index.useable.scss
中寫入樣式
// theme-chalk/index.useable.scssbody { background: red; }// theme-light/index.useable.scssbody { background: green; }
到此,我們的主題樣式都已經(jīng)建好了,現(xiàn)在要將主題應(yīng)用上去
在vue.config.js中增加style-loader/useable
vue-cli2根vue-cli3的配置區(qū)別還是挺大的,我在配置的過(guò)程中遇到很多坑,因?yàn)関ue-cli3沒(méi)有了webpack.config.js文件,我們?cè)谂渲脀ebpack的時(shí)候無(wú)法根據(jù)老文檔來(lái)配置,需要熟悉cli3的webpack-chain來(lái)鏈?zhǔn)叫薷呐渲茫俏臋n很少,配置的過(guò)程中異常困難。
在配置文件中chainWebpack鏈?zhǔn)叫薷膚ebpack配置就能成功應(yīng)用loader了,話不多說(shuō),直接上代碼,
// 換膚loader const scss = config.module.rule('scss').toConfig(); const useable = { ...scss.oneOf[3], test: //.useable.scss$/ }; useable.use = [...useable.use]; useable.use[0] = { loader: 'style-loader/useable' }; config.module.rule('scss').merge({ oneOf: [useable] });
使用主題
在準(zhǔn)備工作都做好后,接下來(lái)我們開(kāi)始使用主題樣式。
之前說(shuō)的為什么要用style-loader
來(lái)做換膚呢?是因?yàn)閟tyle-loader提供了useable這一API,可動(dòng)態(tài)加載刪除link文件。具體詳情請(qǐng)自行去看看style-loader。
在src目錄下,創(chuàng)建theme.js文件
const cache = {};const themeAction = { chalk() { if (!cache.chalk) { cache.chalk = import('./styles/theme-chalk/index.useable.scss'); } return cache.chalk; }, light() { if (!cache.light) { cache.light = import('./styles/theme-light/index.useable.scss'); } return cache.light; }};let current = null;async function setTheme(theme) { if (themeAction[theme]) { const style = await themeAction[theme](); if (current) { current.unref(); } style.ref(); current = style; }}window.setTheme = setTheme;export default setTheme;
在main.js中,引入theme.js。
import setTheme from './theme'// 使用主題setTheme('chalk')
重啟服務(wù),查看效果
在實(shí)際項(xiàng)目中,可根據(jù)傳入的主題(chalk/light),動(dòng)態(tài)切換主題色,同時(shí)也可根據(jù)業(yè)務(wù)需求,創(chuàng)建多個(gè)主題。我們只需要在index.useable.scss文件中寫樣式變量即可。
總結(jié)
以上所述是小編給大家介紹的基于webpack4+vue-cli3項(xiàng)目實(shí)現(xiàn)換膚功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注