之前是用uniapp开发一个聊天室,发送和显示的主要代码如下。
<unicloud-db where="state==true" v-slot:default="{data, loading, error, options}"
collection="..." field="...">
<view class="chat">
<!-- chat主体,这里省略不写 -->
<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
<view class="uni-textarea">
<textarea v-model="text" maxlength="300" confirm-type="send" @confirm="handleSend"
:show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" @focus="focus"
@blur="blur" auto-height></textarea>
</view>
<button @click="text?send():''" class="send-btn">发送</button>
</view>
</view>
</view>
</unicloud-db>
collection和field填自己的就行。
methods: {
//.....
send() {
const db = uniCloud.database();
const guestbookTable = db.collection('guestbook-2')
let res = guestbookTable.add({
"text": this.text,
})
this.text = '';
this.$forceUpdate();
this.scrollToBottom()
uni.showToast({
title:"发送成功",
})
}
}
在发送之后没有办法立刻把数据库新增的数据推到页面中显示。要刷新或者重进一次才能够出新数据,聊天如果不能即时显示也就不能被称为聊天了。这个问题一直困扰了好久都没有找到方法,也试过使用forceupdate等等方法,但都没有作用。今天在开发别的页面时,无意间翻官方的文档,立刻解决了。
udb前端组件的loadData方法:
this.$refs.udb.loadData() //udb为unicloud-db组件的ref属性值
更改后的send函数如下:加了一行上述代码即可,再加个ref。
<unicloud-db ref="udb" where="state==true" v-slot:default="{data, loading, error, options}"
collection="..." field="...">
methods: {
//.....
send() {
const db = uniCloud.database();
const guestbookTable = db.collection('...')
let res = guestbookTable.add({
"text": this.text,
})
this.text = '';
this.$refs.udb.loadData();
this.scrollToBottom()
uni.showToast({
title:"发送成功",
})
}
}