Uniapp在数据更新后立刻更新组件的方法

之前是用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:"发送成功",
				})
			}
}

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值