利用styleSheets快速生成一個圖示庫介面
&01.需求
需求: 實現一個圖示庫的選擇介面,展示UI庫中所有的圖示並提供選擇功能
- ICON庫——
iview
UI 共 860 個
&02.實現思路
思路從 iview
CSS 樣式表中 提取所有的 .ivu-icon
的樣式,並處理成陣列 利用 v-for
實現迴圈渲染
CSSStyleDeclaration.parentRule屬性返回當前規則所屬的那個樣式塊(CSSRule 例項)。如果不存在所屬的樣式塊,該屬性返回null。
var declaration = document.styleSheets[0].rules[0].style; declaration.parentRule === document.styleSheets[0].rules[0]
&03.程式碼塊
注意!!!
- styleSheets 、 cssRules 都是
Object
型別,其本身定義了一個length
的鍵值; - 除
length
外每個鍵值從0開始自增,所以在取值時以 styleSheets[0] 去取 ,並非陣列的取值; - 還有一點要注意的是:在開發環境下,css未被打包時肯能會有多個styleSheets存在、而生產環境下css會預設被統一打成一份即只存在一個styleSheets
/** * 提取ICON */ getIconsArr () { let data = []; let docSheets = document.styleSheets||[]; for ( let sheets ofdocSheets ) { if(sheets.cssRules.length!==0){ for (let index in sheets.cssRules) { let reStr = sheets.cssRules[index].selectorText||sheets.cssRules[index].cssText; if(reStr!=undefined&&reStr.startsWith('.ivu-icon-')){ data.push(reStr.split('::')[0].slice(10,reStr.split('::')[0].length)) ; } } } } // 陣列去重 let set = new Set(data); this.icons = new Array(...set); }
迴圈生成圖示
<Icon :type="ico" size="large"></Icon>
語法基於 iview
UI庫用法
<h1>共 {{icons.length||0}} 個圖示</h1> <section class="menu-icons-wrap"> <divv-for="(ico,index) in icons" :key="'ico_'+index" @click="$store.commit('iconClick',ico)" class="menu-icons-items" :class="{'menu-icons-items-selected':curIcon==ico}"> <Icon :type="ico" size="large"></Icon> <span>{{ico}}</span> </div> </section>