寫在前面:從零開發一款自己的小程序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組件的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文件了。
未完待續、、