<view class="page"><scroll-view:upper-threshold="0":scroll-y="true"class="message-main"@scroll="scroll":scroll-top="lastMessagePosition"><view class="message-content" id="messageContent"><viewclass="message-content-message":key="index"v-for="(item, index) of message"@click="toBottom">消息{{ item }}</view></view></scroll-view><view class="send-message"><input class="input" type="text" v-model="messageText" /><button class="send-btn" @click="send">发送</button></view></view>
export default { data () { return { message: [16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], lastMessagePosition: 0, messageContentDomHeight: 0, messageText: '' } }, onReady () { const query = uni.createSelectorQuery().in(this) query .select('#messageContent') .boundingClientRect((data) => { this.messageContentDomHeight = data.height }) .exec() }, methods: { scroll (e) { if (e.detail.scrollTop === 0) { // 触顶 this.getMoreMessage() } }, getMoreMessage () { uni.showLoading() setTimeout(() => { var newMessage = [] for (let i = 1; i < 11; i++) { newMessage.unshift(this.message[0] + i) } this.message = [...newMessage, ...this.message] this.lastMessagePosition += 0.01 // 防止两次值一样,scroll-view不滚动 uni.hideLoading() this.$nextTick(() => { const query = uni.createSelectorQuery().in(this) query .select('#messageContent') .boundingClientRect((data) => { this.lastMessagePosition = data.height - this.messageContentDomHeight this.messageContentDomHeight = data.height }) .exec() }) }, 500) }, toBottom () { this.lastMessagePosition = this.messageContentDomHeight }, send () { this.message.push(this.messageText) this.$nextTick(() => { const query = uni.createSelectorQuery().in(this) query .select('#messageContent') .boundingClientRect((data) => { this.messageContentDomHeight = data.height this.toBottom() }) .exec() }) this.messageText = '' } } }
.page { width: 100vw; height: 100vh; position: relative; .message-main { width: 100%; height: calc(100% - 120upx); } .send-message { width: 100%; height: 120upx; display: flex; align-content: center ; justify-content: space-between; background: #fff; padding: 20upx; .input{ width: 80%; height: 80upx; line-height: 90upx; background: #f1f1f1; } .send-btn{ width: 120upx; height: 80upx; background: #f1f1f1; } } } .message-content { .message-content-message { height: 100upx; &:nth-child(odd) { background: #f1f1f1; } } }