uniapp实现简易聊天的模版代码
时间: 2023-10-01 12:11:13 浏览: 89
以下是一个简单的uniapp实现聊天的模板代码:
```html
<template>
<view class="container">
<scroll-view class="chat-box" scroll-y="true" scroll-into-view="{{scrollIntoView}}" scroll-with-animation="{{true}}">
<view wx:for="{{chatList}}" wx:key="{{index}}">
<view class="chat-item {{item.type}}">
<text class="chat-text">{{item.content}}</text>
</view>
</view>
</scroll-view>
<view class="input-box">
<input class="input-text" type="text" placeholder="请输入聊天内容" bindinput="onInput" value="{{inputValue}}"/>
<button class="send-btn" bindtap="onSend">发送</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
inputValue: '', // 输入框的值
chatList: [], // 聊天内容列表
scrollIntoView: '', // 滚动到的位置
}
},
methods: {
onInput(e) {
this.inputValue = e.detail.value
},
onSend() {
if(!this.inputValue) return
// 添加聊天记录
this.chatList.push({
type: 'me',
content: this.inputValue
})
this.inputValue = ''
// 模拟对方回复
setTimeout(() => {
this.chatList.push({
type: 'other',
content: '你好'
})
this.scrollIntoView = `chat${this.chatList.length - 1}`
}, 1000)
},
},
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
height: calc(100vh - 140rpx);
padding: 20rpx;
}
.chat-box {
flex: 1;
margin-bottom: 20rpx;
}
.chat-item {
display: flex;
margin-bottom: 10rpx;
max-width: 70%;
word-wrap: break-word;
}
.chat-item.me {
justify-content: flex-end;
}
.chat-item.other {
justify-content: flex-start;
}
.chat-text {
padding: 10rpx;
border-radius: 10rpx;
background-color: #f5f5f5;
}
.input-box {
display: flex;
justify-content: space-between;
align-items: center;
height: 80rpx;
}
.input-text {
flex: 1;
margin-right: 20rpx;
padding: 20rpx;
border-radius: 10rpx;
background-color: #f5f5f5;
border: none;
}
.send-btn {
padding: 20rpx;
border-radius: 10rpx;
background-color: #007aff;
color: #fff;
border: none;
}
</style>
```
这是一个简单的聊天页面模板,实现了向对话框中发送消息,并模拟了对方回复的过程。你可以在此基础上进行修改和扩展。
阅读全文