小程式使用之自定義元件
今天要介紹的是小程式的 自定義元件 ,類似的在做android 開發的過程中會用到自定義view,封裝成通用的元件可以在不同頁面裡重複使用;可以將複雜的頁面拆分成多個低耦合的模組,便於程式碼的維護。
一個自定義元件由 js
json
wxml
wxss
4個檔案組成,微信開發者工具裡新建 選擇 Component,會自動建立這個4個檔案, json檔案裡設定:
{ "component": true }
image.gif
這一組檔案可以當做自定義元件使用。
注‘Android技術交流群878873098,歡迎大家加入交流,暢談!本群有免費學習資料視訊’並且免費分享原始碼解析視訊
一個簡單的例子,自定義item當做元件使用。
在元件的wxml檔案裡碼上頁面元素
<view> <text>{{txt}}</text> <view class='content'> <view> <slot></slot> <text class='title'>{{title}}</text> </view> <text class='subTitle'>{{subTitle}}</text> </view> </view>
image.gif
元件提供 <slot>
節點,用於承載元件在引用時提供的子節點,可以當做佔位的標誌,後面可以將檢視直接填充到此節點。
wxss是對應元件的樣式
.content{ display: flex; justify-content: space-between; align-items: center; padding-left: 10px; padding-right: 10px } .title{ color: #424242 } .subTitle{ color: #939393; font-size: 16px }
image.gif
js檔案裡的Component構造器可以指定元件的屬性、資料、方法等。
/** * 元件的屬性列表 */ properties: { title: { type: String, //屬性型別 value: "--" //屬性初始值 }, subTitle: { type: String, value: "--" }, }
image.gif
屬性列表裡的值對應渲染在元件的wxml裡。
/** * 元件的初始資料 */ data: { txt:"顏色" },
image.gif
元件的內部資料用於wxml的渲染。
在需要用到元件的頁面json檔案裡新增,注意路徑是絕對路徑:
{ "usingComponents": { "item": "/component/item/item" //絕對路徑 } }
image.gif
wxml頁面內直接使用 <item>
標籤,該標籤下的節點text 用於填充到 <solt>
內
<view> <item title="紅色" subTitle="red"> <text>1、</text> </item> </view>
image.gif
注‘Android技術交流群878873098,歡迎大家加入交流,暢談!本群有免費學習資料視訊’並且免費分享原始碼解析視訊
一個簡單的頁面渲染

image
元件也可以接受外部傳入的樣式,在元件的js檔案 Component 構造器裡
Component({ externalClasses: ['title-class'] })
image.gif
注意這裡使用*-class 的形式定義,在元件的wxml裡
<text class='title-class'>{{title}}</text>
image.gif
外部使用的話,可以看到外部的樣式傳遞給元件使用。
//wxml檔案 <item title-class="red-class" title="紅色" subTitle="red"> <text>1、</text> </item> //wxss .red-class{ color: red }

image
注‘Android技術交流群878873098,歡迎大家加入交流,暢談!本群有免費學習資料視訊’並且免費分享原始碼解析視訊
一個簡單的元件的例子完成,實際專案中,通過自定義元件便於在不同的頁面中重複使用。