小程序自定義組件

  • 參數(shù)options配置

    組件wxml模板

    <view class="wrapper">
      <slot name="before"></slot>
      <view>這里是組件的內(nèi)部細節(jié)</view>
      <slot name="after"></slot>  //用不同的 name 來區(qū)分
    </view>
    

    組件js模板

    Component({
     options: {
        multipleSlots: true, // 默認情況下,一個組件的wxml中只能有一個slot。
                                      //需要使用多slot時,可以在組件js中聲明啟用。
        styleIsolation: 'isolated',//組件樣式隔離。
        //isolated雙向隔離;
        //apply-shared僅接受頁面(父);
        // shared雙向影響包括同樣設置該參數(shù)的其他自定義組件
        addGlobalClass: true,
        //表示頁面 wxss 樣式將影響到自定義組件,等價于設置 styleIsolation: apply-shared
        pureDataPattern:/^_/ 
        // 指定所有 _ 開頭的數(shù)據(jù)字段為純數(shù)據(jù)字段  正則
     }
    })
    

    純數(shù)據(jù)字段:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/pure-data.html

  • 參數(shù)externalClasses:引用外部樣式類

    組件 custom-component.js

    Component({
      externalClasses: ['my-class']
    })          
    

    組件 custom-component.wxml

    <custom-component class="my-class">這段文本的顏色由組件外的 class 決定</custom-component>         
    
    <!-- 頁面的 WXML引用組件插入樣式,可引入多個 -->
    <my-component my-class="red-text large-text" />
    
    <!-- 頁面的 WXML樣式 -->
    .red-text {
      color: red;
    }
    .large-text {
      font-size: 1.5em;
    }
    
  • 參數(shù)properties:接收(父)頁面參數(shù)

    Component({
      properties: {
         min: {
          type: Number,//屬性的類型
          optionalTypes: [String, Object],//屬性的類型(可以指定多個)
          value: 0,//屬性的初始值
          observer: function(newVal, oldVal) {
            // 屬性值變化時執(zhí)行
            }
         }
       }
    })
    
    屬性的類型可以為 String Number Boolean Object Array 其一,也可以為 null 表示不限制類型。
    多數(shù)情況下,屬性最好指定一個確切的類型,防止數(shù)字與字符數(shù)字混亂
    
  • 參數(shù)observers:數(shù)據(jù)監(jiān)聽器

    Component({
      attached: function() {
        this.setData({
          numberA: 1,
          numberB: 2,
      })
    },
    observers: {
      'numberA, numberB': function(numberA, numberB) {
        // 在 numberA 或者 numberB 被設置時,執(zhí)行這個函數(shù)
          this.setData({
            sum: numberA + numberB
          })
        }
      }
    })
    使用通配符 ** 可以監(jiān)聽全部 setData
    說明observers只能在Component中使用,沒法在Page中使用
    Observer屬于小程序的新功能,只能在高版本微信使用,低版本微信無法使用
    若在page中監(jiān)聽watch需擴展
    
  • 參數(shù)lifetimes:組件內(nèi)周期函數(shù)

    Component({
      lifetimes: {
        attached: function() {
        // 在組件實例進入頁面節(jié)點樹時執(zhí)行
        },
        detached: function() {
        // 在組件實例被從頁面節(jié)點樹移除時執(zhí)行
        },
      }
    })
    

    參數(shù)

    created    =》在組件實例剛剛被創(chuàng)建時執(zhí)行
    attached   =》在組件實例進入頁面節(jié)點樹時執(zhí)行
    ready      =》在組件在視圖層布局完成后執(zhí)行
    moved      =》在組件實例被移動到節(jié)點樹另一個位置時執(zhí)行
    detached   =》在組件實例被從頁面節(jié)點樹移除時執(zhí)行
    error      =》每當組件方法拋出錯誤時執(zhí)行
    
  • 參數(shù)pageLifetimes:組件所在頁面周期函數(shù)

    Component({
      pageLifetimes: {
        show: function() {
        // 頁面被展示
        },
        hide: function() {
         // 頁面被隱藏
      },
      resize: function(size) {
        // 頁面尺寸變化
      }
     }
    })
    

    參數(shù)

    show     =》組件所在的頁面被展示時執(zhí)行
    hide     =》組件所在的頁面被隱藏時執(zhí)行
    resize   =》組件所在的頁面尺寸變化時執(zhí)行
    
  • 參數(shù)behaviors:組件間代碼共享

    每個 behavior 可以包含一組屬性、數(shù)據(jù)、生命周期函數(shù)和方法
    組件引用它時,它的屬性、數(shù)據(jù)和方法會被合并到組件中,生命周期函數(shù)也會在對應時機被調(diào)用
    每個組件可以引用多個 behavior ,behavior 也可以引用其他 behavior
    

    組件模板

    <view class="wrapper">
      <view>{{myBehaviorProperty}}</view>
      <view>{{myProperty}}</view>
      <button bindtap="myBehaviorMethod">點擊觸發(fā) behavior 方法</button>
    </view>
    

    組件 my-component.js

    var myBehavior = require('my-behavior')
      Component({
        behaviors: [myBehavior],
        properties: {
              myProperty: {
                  type: String
              }
        }
    })
    

    my-behavior.js

    module.exports = Behavior({
      behaviors: [],
      properties: {
      myBehaviorProperty: {
        type: String
      }
    },
    methods: {
        myBehaviorMethod: function () {
          console.log('log from my-behavior.js')
        }
    }
    })
    

    引用組件的頁面模版

    <view>
      <my-component my-behavior-property="behavior-property" my-property="my-property">
      </my-component>
    </view>
    

    內(nèi)置 behaviors

    Component({
      behaviors: ['wx://form-field']
    })
    ['wx://form-field']表單控件的行為
    Component({
    behaviors: ['wx://component-export'],
    export() {
      return { myField: 'myValue' }
    }
    })
    ['wx://component-export']使自定義組件支持 export 定義段。這個定義段可以用于指定組件被 selectComponent 調(diào)用時的返回值
    

    this.selectComponent用于父級直接調(diào)用子組件

    <!-- 使用自定義組件時 -->
    <my-component id="the-id" />
    this.selectComponent('#the-id') // 等于 { myField: 'myValue' }
    
  • 參數(shù)relations:組件間聯(lián)系

    必須在兩個組件定義中都加入relations定義,否則不會生效
    

    頁面中引用組件

    <custom-ul>
      <custom-li> item 1 </custom-li>
      <custom-li> item 2 </custom-li>
    </custom-ul>
    

    custom-ul.js

    Component({
        relations: {
          './custom-li': {
          type: 'child', // 關(guān)聯(lián)的目標節(jié)點應為子節(jié)點
          linked: function(target) {
          // 每次有custom-li被插入時執(zhí)行,target是該節(jié)點實例對象,觸發(fā)在該節(jié)點attached生命周期之后
          },
          linkChanged: function(target) {
          // 每次有custom-li被移動后執(zhí)行,target是該節(jié)點實例對象,觸發(fā)在該節(jié)點moved生命周期之后
          },
          unlinked: function(target) {
          // 每次有custom-li被移除時執(zhí)行,target是該節(jié)點實例對象,觸發(fā)在該節(jié)點detached生命周期之后
        }
      }
    },
    methods: {
      _getAllLi: function(){
      // 使用getRelationNodes可以獲得nodes數(shù)組,包含所有已關(guān)聯(lián)的custom-li,且是有序的
      var nodes = this.getRelationNodes('./custom-li')//組件地址
      }
    },
    ready: function(){
      this._getAllLi()
    }
    })
    

    custom-li.js

    Component({
      relations: {
      './custom-ul': {
        type: 'parent', // 關(guān)聯(lián)的目標節(jié)點應為父節(jié)點
      }
    }
    })
    

    參數(shù)

    type        =》目標組件的相對關(guān)系,可選的值為 parent 、 child 、 ancestor(祖先) 、 descendant(子孫)
    inked       =》關(guān)系生命周期函數(shù),當關(guān)系被建立在頁面節(jié)點樹中時觸發(fā),觸發(fā)時機在組件attached生命周期之后
    linkChanged =》關(guān)系生命周期函數(shù),當關(guān)系在頁面節(jié)點樹中發(fā)生改變時觸發(fā),觸發(fā)時機在組件moved生命周期之后
    unlinked    =》關(guān)系生命周期函數(shù),當關(guān)系脫離頁面節(jié)點樹時觸發(fā),觸發(fā)時機在組件detached生命周期之后
    target      =》如果這一項被設置,則它表示關(guān)聯(lián)的目標節(jié)點所應具有的behavior,所有擁有這一behavior的組件節(jié)點都會被關(guān)聯(lián)
    

    詳解:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/relations.html

  • 組件擴展

    // behavior.js
    module.exports = Behavior({
      definitionFilter(defFields) {
        defFields.data.from = 'behavior'
      },
    })
    
    // component.js
    Component({
    data: {
    from: 'component'
    },
    behaviors: [require('behavior.js')],
    ready() {
    console.log(this.data.from) // 此處會發(fā)現(xiàn)輸出 behavior 而不是 component
    }
    })
    

    組件擴展watch和computed
    官方擴展包https://github.com/wechat-miniprogram/computed

  • 組件內(nèi)方法

    setData設置data并執(zhí)行視圖層渲染
    triggerEvent用于子傳父通信事件
    詳情https://developers.weixin.qq.com/miniprogram/dev/reference/api/Component.html

  • 組件內(nèi)可調(diào)用的屬性和方法

    組件的方法、生命周期函數(shù)和屬性 observer 中通過 this 訪問

    is          =》組件的文件路徑
    id          =》節(jié)點id
    dataset     =》節(jié)點dataset
    data        =》組件數(shù)據(jù),包括內(nèi)部數(shù)據(jù)和屬性值
    properties  =》組件數(shù)據(jù),包括內(nèi)部數(shù)據(jù)和屬性值(與 data 一致)
    
  • 抽象節(jié)點

    selectable-group.wxml

    <view wx:for="{{labels}}">
      <label>
        <selectable disabled="{{false}}"></selectable>//抽象子組件
          {{item}}
      </label>
    </view>
    

    selectable-group.json

    {
      "componentGenerics": {
        "selectable": true
      }
    }
    
    或者設置默認抽象頁面
    
    {
      "componentGenerics": {
        "selectable": {
          "default": "path/to/default/component"
      }
    }
    }
    

    在頁面中引用

    <selectable-group generic:selectable="custom-radio" />//生成單選框
    <selectable-group generic:selectable="custom-checkbox" />//生成多選框
    

    在頁面json配置

    {
      "usingComponents": {
          "custom-radio": "path/to/custom/radio",
          "custom-checkbox": "path/to/custom/checkbox"
      }
    }
    

    詳解:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/generics.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容