
1.定義子組件Tabs
<!-- Tabs.wxml組件 -->
<view class="tab_wrapper">
<view class="tab">
<view class="{{currentIndex===index?'active':''}} title" wx:for="{{tabs}}" wx:key="id" bindtap="itemTap" data-index="{{index}}">
{{item.name}}
</view>
</view>
<view class="tabs_content">
<slot></slot>
</view>
</view>
// components/Tabs/Tabs.js
Component({
/**
* 組件的屬性列表
*/
properties: {
tabs: {
type: Array,
value: [],
},
},
/**
* 組件的初始數據
*/
data: {
currentIndex: 0,
},
/**
* 組件的方法列表
*/
methods: {
itemTap(e) {
const index = e.currentTarget.dataset.index;
this.setData({
currentIndex: index,
});
this.triggerEvent('itemTap', { index }); //子組件發送事件itemTap和一個obj作為參數
},
},
});
2.使用子組件
<!-- goods_list.wxml -->
<!-- 商品列表 開始 -->
<view>
<Tabs tabs="{{tabs}}" binditemTap="ItemTap">
<block wx:if="{{currentIndex===0}}">0</block>
<block wx:if="{{currentIndex===1}}">1</block>
<block wx:if="{{currentIndex===2}}">2</block>
</Tabs>
</view>
<!-- 商品列表 結束 -->
// pages/goods_list/goods_list.js
Page({
/**
* 頁面的初始數據
*/
data: {
tabs: [
{ id: 0, name: '綜合' },
{ id: 1, name: '銷量' },
{ id: 2, name: '價格' },
],
currentIndex: 0,
},
// 監聽子組件傳遞的事件
ItemTap(e) {
this.setData({
currentIndex: e.detail.index, //e.detail.index是子組件傳遞過來的index
});
},