模拟智能客服聊天,每次发送信息后自动滚动到底部
- 需要设置固定高度,这样视图里面内容当只有超过该高度才会有滚动效果
- 需要设置
scroll-with-animation=true,可以出现慢慢滚动到底部效果
<scroll-view class="scroll-view" :scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true">
<view class="official-content">
<view class="title">
猜你想问
</view>
<view class="guess" v-for="(item,index) in guessList" :key='index' @click="sendMessage(item)">
{{item}}
</view>
<view class="title">
常见问题
</view>
<view class="list">
<view class="question flex-justify" v-for="(item,index) in questions" :key="index"
@click="sendMessage(item)">
<view>
{{item}}
</view>
<view class="right-arrow"></view>
</view>
</view>
<view class="message">
<view :class="{'text-right':1===item.source}" v-for="(item,index) in messageList" :key="index">
<view class="time">{{$util.timeStampTurnTime(item.time,'hourMinute')}}</view>
<view :class="1===item.source?'request':'response'">{{item.text}}</view>
</view>
</view>
</view>
</scroll-view>
export default {
data() {
return {
scrollTop: 0, //滚动条位置
scrollHeight: 0, // 滚动视图的高度
guessList: ['为何购买xxx?', '什么叫xxx?', '如何赚钱?', '如何获得xxx?'],
questions: ['如何注册成为会员?', '如何提现?', 'xxxx有什么用?', 'xx如何激活?'],
messageList: []
}
},
mounted() {
// 先获取滚动视图的高度
this.initScrollHeight();
},
methods: {
initScrollHeight() {
uni.createSelectorQuery()
.in(this)
.select('.scroll-view')
.boundingClientRect(data => {
if (data) {
this.scrollHeight = data.height
}
})
.exec();
},
// 获取内容高度
initContentHeight() {
uni.createSelectorQuery()
.in(this)
.select('.official-content')
.boundingClientRect(data => {
if (data) {
let top = data.height - this.scrollHeight;
if (top > 0) {
this.scrollTop = top;
}
}
})
.exec();
},
sendMessage(item) {
this.message = item
this.messageList.push({
text: item,
time: new Date().getTime() / 1000,
source: 1
})
setTimeout(() => {
this.messageList.push({
text: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文',
time: new Date().getTime() / 1000,
source: 2
})
}, 100)
setTimeout(()=>{
this.initContentHeight()
},100)
}
}
}
.scroll-view {
height: calc(100vh - 500rpx);
background-color: #fff;
}
效果图如下: