
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
});
},