微信小程序开发 实现好友列表以及聊天信息 代码
时间: 2023-12-11 08:04:43 浏览: 50
以下是微信小程序实现好友列表和聊天信息的代码示例:
### 好友列表页面
wxml代码:
```html
<view class="friends-list">
<scroll-view scroll-y="true">
<view wx:for="{{friendsList}}" wx:key="{{item.id}}" class="friend-item" bindtap="gotoChat">
<view class="avatar"></view>
<view class="friend-info">
<view class="friend-name">{{item.name}}</view>
<view class="last-message">{{item.lastMessage}}</view>
</view>
</view>
</scroll-view>
</view>
```
js代码:
```javascript
Page({
data: {
friendsList: [
{
id: 1,
name: '小明',
lastMessage: '你好!',
},
{
id: 2,
name: '小红',
lastMessage: '在干嘛?',
},
{
id: 3,
name: '小刚',
lastMessage: '晚上一起吃饭吗?',
},
],
},
gotoChat(e) {
const friendId = e.currentTarget.dataset.friendId;
wx.navigateTo({
url: `/pages/chat/chat?friendId=${friendId}`,
});
},
});
```
### 聊天页面
wxml代码:
```html
<view class="chat">
<scroll-view scroll-y="true">
<view wx:for="{{messageList}}" wx:key="{{item.id}}" class="message-item">
<view class="avatar"></view>
<view class="message-info">
<view class="message-text">{{item.text}}</view>
</view>
</view>
</scroll-view>
<view class="input-box">
<input placeholder="请输入消息" bindinput="inputMessage" value="{{inputValue}}" />
<button bindtap="sendMessage">发送</button>
</view>
</view>
```
js代码:
```javascript
Page({
data: {
friendId: null,
messageList: [
{
id: 1,
from: 1,
to: 2,
text: '你好!',
},
{
id: 2,
from: 2,
to: 1,
text: '在干嘛?',
},
],
inputValue: '',
},
onLoad(options) {
const friendId = options.friendId;
this.setData({
friendId,
});
},
inputMessage(e) {
const inputValue = e.detail.value;
this.setData({
inputValue,
});
},
sendMessage() {
const { messageList, friendId, inputValue } = this.data;
const newMessage = {
id: messageList.length + 1,
from: 1, // 假设1为自己的id
to: friendId,
text: inputValue,
};
messageList.push(newMessage);
this.setData({
messageList,
inputValue: '',
});
},
});
```
以上代码仅供参考,实际使用中需要根据需求进行适当修改。