1. 程式人生 > >從零開發一款自己的小程式UI元件庫(二)

從零開發一款自己的小程式UI元件庫(二)

寫在前面:從零開發一款自己的小程式UI元件庫(一)

上節我們講到初始化元件庫模板、模板檔案概述、模板上傳npm以及npm包檔案下載至本地並運用到專案。這節我們繼續,內容主要有基礎UI元件庫的搭建(button元件的例項)以及如何在本地使用npm link除錯npm包專案。

本節所用到的物料:mineui-weapp元件庫v1.1、weapp-for-mineui程式v1.1

1.開發基礎元件button

我們上節有提到,要開發元件庫的話,需要在官方單元件模板的基礎上,①修改tools目錄下的config.js檔案、②新建src下的button元件目錄和button目錄下的四個index檔案以及③新建承載button元件的button頁面

①tools目錄下的config.js檔案,修改entry: ['index'],為:entry: ['index', 'button/index']。

②在src目錄下新建button目錄和button目錄下的四個index檔案【index.wxss、index.json、index.js、index.wxml】,並填充基礎內容

修改index.wxss檔案:

@import "../common.wxss";

.mine-button--default {
  color: #333;
  background-color: #fff;
  border: 1px solid #eee
}

.mine-button--primary {
  color: #fff;
  background-color: #07c160;
  border: 1px solid #07c160
}

.mine-button--info {
  color: #fff;
  background-color: #1989fa;
  border: 1px solid #1989fa
}

.mine-button--danger {
  color: #fff;
  background-color: #f44;
  border: 1px solid #f44
}

.mine-button--warning {
  color: #fff;
  background-color: #ff976a;
  border: 1px solid #ff976a
}

修改index.json檔案:

{
  "component": true,
  "usingComponents": {}
}

修改index.js檔案:

Component({
  properties: {
    type: {
      type: String,
      value: 'primaty'
    }
  },
  methods: {
    onClick() {
      this.$emit('click')
    }
  }
})

修改index.wxml檔案:

<button class="mine-button--{{type}}" bindtap="onClick">   <slot /> </button>

③新建承載button元件的button頁面

修改在tools/demo目錄下的app.json檔案,pages陣列下增加 "pages/button/index" 的,並在tools/demo/pages下新增button目錄及其下的index檔案,這裡修改json、js、wxml檔案

修改index.json檔案:

{
  "usingComponents": {
    "comp": "../../components/button"
  }
}

修改index.js檔案:

Page({})

修改index.wxml檔案:

<mine-button type="danger">I'm a button</mine-button>

在根目錄下執行:

npm run watch

使用微信開發者工具匯入預覽miniprogram_dev目錄,並將預覽模式轉到“pages/button/index”目錄下,即可看到一個紅色的button,內容為:I'm a button

這時,我們修改tools/demo/pages/button/index.wxml檔案:

<mine-button type="primary">I'm a primary button</mine-button>

可以實時看到開發者工具預覽按鈕變成綠色的button,內容為:I'm a primary button

 

這裡一個簡單的button元件就編寫完成了,那麼如何豐富它的屬性讓它適應更多的場景呢?

2.豐富button元件

在上面的基礎button元件中,我們只配置了button的type即按鈕的背景顏色和文字顏色。但是通常我們使用到button時,還會自定義按鈕背景顏色、按鈕文字顏色及大小、按鈕的大小、按鈕的形狀、按鈕的loading狀態以及按鈕的open-type等等,這就需要我們修改src/button下的index檔案了。

 

未完待續、、

&n