写一个微信小程序基本聊天界面
时间: 2024-06-08 12:07:35 浏览: 83
以下是一个简单的微信小程序基本聊天界面的代码:
```
<!-- index.wxml -->
<view class="container">
<scroll-view class="chat-view" scroll-y="true" scroll-into-view="{{toView}}" scroll-with-animation>
<block wx:for="{{chatList}}" wx:key="index">
<view class="chat-item {{item.isMe ? 'me' : 'other'}}">
<view class="avatar">
<image src="{{item.avatarUrl}}"></image>
</view>
<view class="content">
<text>{{item.content}}</text>
</view>
</view>
</block>
<view id="{{toView}}"></view>
</scroll-view>
<view class="input-box">
<input class="input" placeholder="请输入消息" value="{{inputValue}}" bindinput="onInput"></input>
<button class="send-btn" bindtap="onSend">发送</button>
</view>
</view>
```
```
/* index.wxss */
.container {
display: flex;
flex-direction: column;
height: 100%;
}
.chat-view {
flex: 1;
padding: 20rpx;
}
.chat-item {
display: flex;
flex-direction: row;
margin-bottom: 20rpx;
}
.me {
justify-content: flex-end;
}
.other {
justify-content: flex-start;
}
.avatar {
width: 60rpx;
height: 60rpx;
border-radius: 50%;
overflow: hidden;
margin-right: 20rpx;
}
.avatar image {
width: 100%;
height: 100%;
object-fit: cover;
}
.content {
flex: 1;
background-color: #f2f2f2;
border-radius: 10rpx;
padding: 20rpx;
}
.content text {
font-size: 28rpx;
color: #333;
}
.input-box {
display: flex;
flex-direction: row;
height: 100rpx;
align-items: center;
padding: 20rpx;
background-color: #f2f2f2;
}
.input {
flex: 1;
height: 60rpx;
border-radius: 30rpx;
border: none;
outline: none;
padding: 0 20rpx;
font-size: 28rpx;
background-color: #fff;
}
.send-btn {
width: 140rpx;
height: 60rpx;
border-radius: 30rpx;
border: none;
outline: none;
margin-left: 20rpx;
font-size: 28rpx;
background-color: #07c160;
color: #fff;
}
.send-btn:active {
background-color: #059c4c;
}
```
```
// index.js
Page({
data: {
chatList: [], // 聊天记录
inputValue: '', // 输入框内容
toView: '', // 滚动到的位置
},
onInput(event) {
this.setData({
inputValue: event.detail.value,
});
},
onSend() {
const { chatList, inputValue } = this.data;
if (!inputValue) return;
const newItem = {
avatarUrl: 'https://placekitten.com/60/60',
content: inputValue,
isMe: true,
};
chatList.push(newItem);
this.setData({
chatList,
inputValue: '',
toView: `chat_${chatList.length - 1}`,
});
},
});
```
以上代码实现了一个简单的聊天界面,包括消息的发送和展示。其中,`chatList` 存储聊天记录,`inputValue` 存储输入框的内容,`toView` 用于控制滚动到的位置。在发送消息时,新建一个消息对象并添加到 `chatList` 中,同时将滚动到最新的一条消息。
阅读全文