小程序自定義組件

一:定義組件

在miniprogram下的目錄下建立一個components文件夾,與pages目錄同級,這個文件夾專門是用來放自定義組件的 例如:在components目錄下建立了一個count文件夾,而後在新建Component,組件名稱命名爲count,微信開發者工具會自動的建立count組件vue

// =============count.wxml==================
<view>
  <view class="count-container">
    <view bindtap="reduce" class="{{count == 1? 'btn-disabled': ''}}}">-</view>
    <input bindinput="handleInput" type="number" value="{{count}}" />
    <view bindtap="add">+</view>
  </view>
</view>

// =============count.js================

// components/count/count.js
Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    count: Number,
  },

  /**
   * 組件的初始數據
   */
  data: {},

  /**
   * 組件的方法列表
   */
  methods: {
    reduce() {
      var count = this.data.count - 1;
      if (count < 1) {
        count = 1;
      }
      this.setData({
        count,
      });
      this.triggerEvent('changeCount', count);
      console.log(this.data.count);
    },

    add() {
      var count = this.data.count + 1;
      this.setData({
        count,
      });
      this.triggerEvent('changeCount', count);
      console.log(this.data.count);
    },

    handleInput(event) {
      this.setData({
        count: event.detail.value,
      });
      this.triggerEvent('changeCount', event.detail.value); // 向外暴露函數
    },
  },
});複製代碼

二:使用組件

在pages目錄下,這裏我建立了一個customComponents頁面react

在要使用頁面對應的customComponents.json中的usingComponents自定義組件的名稱,同時引入組件的路徑json

// customComponents.json
{
  "usingComponents": {
    "count":"/components/count/count"
  }
}複製代碼
// customComponents.wxml

<count count="{{countNum}}" bind:changeCount="handleCount"></count>
<view class="parentText">父組件count:{{countNum}}</view>複製代碼
****// pages/customComponents/customComponents.js
Page({
  /**
   * 頁面的初始數據
   */
  data: {
    countNum: 1,
  },

  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function(options) {},

  // 父組件中自定義綁定的事件
  handleCount(event) {
    this.setData({
      countNum: event.detail, // 獲取子組件傳遞過來的值
    });
  },
});複製代碼

三:小程序中組件的通訊與事件

  • 父傳子小程序

    註釋:properties相似於vue中的props,react中的this.props數組

    • wxml數據綁定:用於父組件向子組件指定屬性設置數據,在子組件中properties對象接收外部(父)組件傳過來的自定義屬性數據,能夠是對象,數組,基本數據類型等。
  • 子傳父微信

    注意:triggerEvent,就至關於vue中的this.$emit('綁定在父組件自定義事件名稱',攜帶的數據)方法的,而在React中是經過this.props.方法接收,調用父組件的方法。微信開發

    • 事件: 用於子組件經過      this.triggerEvent()向父組件傳遞數據,能夠傳遞任意數據,父組件經過綁定綁定監聽事件,從而觸發父組件自定義事件,event.detail是子組件傳遞過來的值。
  • 在父組件中還能夠經過this.selectComponent("類名或ID")方法獲取子組件的實例對象,這樣在父組件中沒必要經過event.detail的方式獲取,能夠直接訪問子組件任意的數據和方法。ide

前提條件:函數

須要在父組件的引用自定義組件上,添加class或id工具

<count
 class="count"
 count="{{countNum}}"
 bind:changeCount="handleCount"
></count>複製代碼

那麼,在父組件中的handleCount中裏調用 this.selectComponent,獲取子組件的實例數據

調用時須要傳入一個匹配選擇器 class與Id均可以,如,this.selectComponent('類或ID')

 handleCount(){
    var count = this.selectComponent('.count'); // 獲取子組件的實例
    this.setData({
      countNum: count.data.count  // 從新賦值setData countNum數據
    })

  }複製代碼
相關文章
相關標籤/搜索