1. 程式人生 > >微信小程序——自定義圖標組件

微信小程序——自定義圖標組件

oba 便在 head 庫項目 using sans dex padding prope

字體圖標在網頁中非常常見了。為了方便在小程序裏面重復使用,自定義了一個圖標組件,方便控制它的大小,顏色,自定義點擊事件。

自定義圖標組件的代碼如下:

下面的代碼是icon文件夾下面的4個文件

技術分享圖片

index.wxml:
<view
  class="custom-class ss-font ss-icon-{{ name }}"
  style="{{ color ? ‘color: ‘ + color : ‘‘ }}; {{ size ? ‘font-size: ‘ + size : ‘‘ }}"
  bind:tap="onClick"
>
  <view wx:if
="{{ info !== null }}" class="ss-icon__info">{{ info }}</view> </view>

上面的 ss-font 和 ss-icon 是根據你在阿裏巴巴圖標庫項目中自定義的,我的如下圖:

技術分享圖片

index.js:

Component({
  options: {
    addGlobalClass: true
  },

  externalClasses: [‘custom-class‘],

  properties: {
    info: null,
    name: String,
    size: String,
    color: String
  },

  methods: {
    onClick() {
      
this.triggerEvent(‘click‘); } } });

上面如果理解有困難的可以先看一下小程序組件介紹大概了解一些基本概念。

index.json:

{
  "component": true
}

index.wxss:

/**
這裏放你的所有圖標的代碼
在阿裏巴巴矢量庫,選擇 Unicode 模式,下載解壓後的iconfont.css裏面的代碼,下面有截圖可供參考
**/
.ss-icon__info {
  color: #fff;
  left: 100%;
  top: -.5em;
  font-size: 0.5em;
  padding: 0 0.3em
; text-align: center; min-width: 1.2em; line-height: 1.2; position: absolute; border-radius: 0.6em; box-sizing: border-box; background-color: #f44; -webkit-transform: translateX(-50%); transform: translateX(-50%); font-family: PingFang SC, Helvetica Neue, Arial, sans-serif; }

技術分享圖片

技術分享圖片

API:

參數說明類型默認值
name 圖標名稱 String -
info 圖標右上角文字提示 String | Number -
color 圖標顏色 String inherit
size 圖標大小,如 16px1em String inherit
custom-style 自定義樣式 String -

使用方法:

在index.json引入該組件:

"usingComponents": {
  "ss-icon": "/components/icon/index"
}

設置name屬性為對應的圖標名稱即可。

<ss-icon name="tel" />

這些圖標就是你自己定義的。像我下面的電話圖標:

技術分享圖片

像什麽顏色,大小的配置可以查看上面的API表格。這裏就不一一贅述了~

微信小程序——自定義圖標組件