邏輯代碼部分主要包括三部分:
在message組件中需要拉取聊天列表信息并且渲染,代碼如下:
<template>
<view class="message">
<block wx:for="{{list}}" wx:for-index="index" wx:for-item="item">
<view class="item" bindtap="select" data-wepy-params="{{item.id}}">
<view class="header">
<image class="img" src="{{item.icon}}"></image>
</view>
<view class="content">
<view class="name">{{item.name}}</view>
<view class="lastmsg">{{item.lastmsg}}</view>
</view>
</view>
</block>
</view>
</template>
<script>
import wepy from 'wepy';
import api from '../common/api';
export default class Message extends wepy.component {
data = {
list: []
};
methods = {
select (evt, id) {
wx.navigateTo({url: 'chat?id=' + id});
}
};
async loadMessage () {
this.list = await api.getMessageList();
this.$apply();
}
}
</script>
message組件中只有一個(gè)數(shù)據(jù)源list,通過自定義方法loadMessage調(diào)用api模塊獲取聊天列表信息進(jìn)行渲染,因?yàn)槭窃谧远x的異步方法中進(jìn)行數(shù)據(jù)綁定,所以需要執(zhí)行this.$apply()讓視圖渲染。同時(shí),組件響應(yīng)頁(yè)面的tap事件select,選中聊天之后跳轉(zhuǎn)至chat頁(yè)面。在chat頁(yè)面進(jìn)行聊天之后,返回到index頁(yè)面時(shí),需要message頁(yè)面再次調(diào)用接口數(shù)據(jù),重新渲染聊天列表頁(yè),這就需要在index頁(yè)面的onShow方法中去讓message組件重新調(diào)用loadMessage方法。這里可以選用 wepy 提供的$boradcast方法或者$invoke方法,代碼如下:
// src/pages/index.wpy
onShow() {
this.$invoke('message', 'loadMessage');
}
這樣就完成了message組件的所有功能,進(jìn)入頁(yè)面渲染列表,點(diǎn)擊消息進(jìn)入聊天頁(yè)面。
在index頁(yè)面中加入狀態(tài)currentTab來標(biāo)記當(dāng)前選中tab。并提供切換tab事件。
src/pages/index:
<template>
<view class="body">
<view class="tab_item tab_message" hidden="{{currentTab != 0}}">
<component id="message"></component>
</view>
<view class="tab_item tab_contact" hidden="{{currentTab != 1}}">
<component id="contact"></component>
</view>
<view class="tab_item tab_discovery" hidden="{{currentTab != 2}}">
<component id="discovery"></component>
</view>
<view class="tab_item tab_me" hidden="{{currentTab != 3}}">
<component id="me"></component>
</view>
<component id="tab"></component>
</view>
</template>
<script>
//....
changeTab (idx) {
this.currentTab = +idx;
this.$apply();
}
</script>
然后在tab組件中的每個(gè)tab中添加bindtap="change" data-wepy-params="{{index}}"事件。
<script>
import wepy from 'wepy';
export default class Tab extends wepy.component {
data = {
active: 0,
};
methods = {
change (evt, idx) {
this.active = +idx;
this.$parent.changeTab(idx);
}
};
}
</script>
在tab組件中,直接通過$parent去調(diào)用父組件的changeTab方法,來達(dá)到實(shí)現(xiàn)tab切換效果:
至此已完成大致雛形,更多代碼還請(qǐng)參考提供源代碼。
更多建議: