WeChatミニアプリにおけるカスタムコンポーネントの実装手法

コンポーネントの構築プロセス

カスタムコンポーネントはcomponentフラグを有効化したJSON設定から開始します。以下は通知バッジコンポーネントの実装例です:

// notification-badge.wxml
<view class="container">
  <view wx:for="{{items}}" wx:key="id" class="badge {{selectedIndex === index ? 'selected' : ''}}" 
        bindtap="handleSelect" data-position="{{index}}">
    {{label}}
  </view>
</view>

// notification-badge.wxss
.container {
  display: flex;
  gap: 12px;
  padding: 8px;
}
.badge {
  padding: 6px 16px;
  border-radius: 20px;
  background: #f0f0f0;
}
.selected {
  background: #1890ff;
  color: white;
}

// notification-badge.json
{
  "component": true,
  "usingComponents": {}
}

// notification-badge.js
Component({
  properties: {
    items: {
      type: Array,
      value: [{id: 1, label: "未読"}, {id: 2, label: "既読"}]
    },
    selectedIndex: {
      type: Number,
      value: 0
    }
  },
  methods: {
    handleSelect(e) {
      const position = e.currentTarget.dataset.position;
      this.setData({ selectedIndex: position });
      this.triggerEvent('selectionChanged', position);
    }
  }
});

親コンポーネントからの統合

使用側ではJSON設定で参照パスを登録します:

{
  "usingComponents": {
    "status-selector": "/components/notification-badge/notification-badge"
  }
}

WXML内での実装はデータバインディングとイベントハンドリングを組み合わせます:

<status-selector items="{{statusOptions}}" 
                selected-index="{{activeStatus}}"
                bind:selectionChanged="updateStatus"/>

双方向通信の実装パターン

親→子のデータ伝達
親コンポーネントがitemsプロパティ経由で配列データを提供します。子コンポーネントはpropertiesで受信します。

子→親のイベント伝達
子コンポーネントのtriggerEventで発火したselectionChangedイベントを、親のupdateStatusメソッドが処理します。

スロット機能の応用

コンポーネント内部で柔軟なコンテンツ配置が可能です:

<view class="layout">
  <slot name="header"/>
  <slot name="content"/>
  <slot name="footer"/>
</view>

親コンポーネントでは<template>タグでスロット内容を定義します。

ライフサイクル管理の実践例

データ取得コンポーネントの初期化/破棄処理:

lifetimes: {
  attached() {
    this.fetchTimer = setInterval(() => {
      if (this.data.remainingTime <= 0) {
        this.triggerEvent('dataExpired');
        return;
      }
      this.setData({ remainingTime: this.data.remainingTime - 1 });
    }, 1000);
  },
  detached() {
    clearInterval(this.fetchTimer);
  }
},
data: {
  remainingTime: 30
}

タグ: wechat-miniprogram custom-components slot-technology component-lifecycle

5月16日 13:47 投稿