ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[toc] # 3.6 接收礼物组件(三) = 自动消失 ## 3.6.1 实现礼物组件自动消失 ``` <template> <!-- 礼物 --> <list style="width: 520rpx; height: 500rpx;" :show-scrollbar="false" :bounce="false"> <cell :ref="'item' + index" insert-animation="default" delete-animation="default" class="flex align-center px-3 pt-3" v-for="(item,index) in gifts" :key="index"> <view style="width: 325rpx; background-image: linear-gradient(to right,#BCABB1, #65AAF0);" class="flex align-center rounded-circle"> <view class="p"> <image :src="item.avatar || defaultAvatar" style="width: 70rpx; height: 70rpx;" class="rounded-circle"></image> </view> <view class="flex-1 flex flex-column justify-center"> <text class="text-white font">{{item.username}}</text> <text class="text-white font-sm">{{item.gift_name}}</text> </view> <view class="p"> <image :src="item.gift_image" style="width: 70rpx; height: 70rpx;" class="rounded-circle"></image> </view> </view> <text class="text-warning font-lg ml-1">X {{item.num}}</text> </cell> </list> </template> <script> const dom = weex.requireModule('dom') export default { data(){ return { defaultAvatar : "/static/tabbar/min.png", gifts : [] } }, created(){ setInterval(()=>{ this.gifts.push({ username : "发送人", avatar : "", gift_name : "蛋糕", gift_image : "/static/gift/3.png", num : 1 }) this.toBottom() this.autoHide() },3000) }, methods : { //置于底部 toBottom(){ this.$nextTick(()=>{ let index = this.gifts.length - 1; let ref = 'item' + index; if(this.$refs[ref]){ dom.scrollToElement(this.$refs[ref][0],{}); } }) }, //自动消失 autoHide(){ if(this.gifts.length){ let timer = setTimeout(()=>{ this.gifts.splice(0,1); },5000) } } } } </script> <style> </style> ``` ## 3.6.2 代码进行封装优化 1. 封装送礼物方法 ``` <script> const dom = weex.requireModule('dom') export default { data(){ return { defaultAvatar : "/static/tabbar/min.png", gifts : [] } }, methods : { //送礼物 send(gift){ this.gifts.push(gift); this.toBottom() this.autoHide() }, //置于底部 toBottom(){ this.$nextTick(()=>{ let index = this.gifts.length - 1; let ref = 'item' + index; if(this.$refs[ref]){ dom.scrollToElement(this.$refs[ref][0],{}); } }) }, //自动消失 autoHide(){ if(this.gifts.length){ let timer = setTimeout(()=>{ this.gifts.splice(0,1); },5000) } } } } </script> ``` 2. 在live.nvue组件中通过ref绑定f-gift组件 ``` <!-- 礼物 --> <f-gift ref="gift"></f-gift> ``` 3. 通过refs获取f-gift内的send方法并进行调用,3秒钟之后传递礼物的数据 ``` <script> import fGift from "../../components/live/f-gift.vue" export default { data(){ return { statusBarHeight : 0 } }, components: { fGift }, onLoad(){ //获取通知栏的高度 let res = uni.getSystemInfoSync(); this.statusBarHeight = res.statusBarHeight; }, mounted(){ setInterval(()=>{ this.$refs.gift.send({ username : "发送人", avatar : "", gift_name : "蛋糕", gift_image : "/static/gift/3.png", num : 1 }) },3000) } } </script> ```