前两天想做一个点赞效果,找了一些插件,感觉不太满意,于是自己做了一个,代码如下:
一、组件代码
<template>
<!-- 点赞效果 -->
<view>
<template v-if="likeList.length">
<view
class="like-effect-wrap"
v-for="(item, index) in likeList"
:key="index"
:style="{ left: item.left + 'px', top: item.top + 'px' }"
>
<image
:src="resource.likeImageUrl"
mode="widthFix"
class="like-image"
></image>
</view>
</template>
</view>
</template>
<script>
export default {
data() {
return {
//资源配置
resource: {
//点赞的图片(自行替换)
likeImageUrl:
this.$cnf.resDomains.image +
'/1/20102/2022/0414/6257ba54a09bdp868.png'
},
//内部维护的队列
likeList: [],
//清理定时器
clearTimer: null,
//点赞时间key
likeTimeKey: '_like_effect_time_key_',
//清理时间间隔
clearTimeCell: 5
}
},
created() {
//开启定时器
this.startTimer()
},
beforeDestroy() {
clearInterval(this.clearTimer)
this.clearTimer = null
this.likeList = []
},
methods: {
//开启定时器
startTimer() {
clearInterval(this.timer)
this.clearTimer = setInterval(() => {
if (this.likeList.length) {
//现在的时间
let currentTime = new Date().getTime() / 1000
//最近一次点赞的时间
let lastLikeTime = this.getCache(this.likeTimeKey)
if (lastLikeTime && currentTime - lastLikeTime > this.clearTimeCell) {
//清空点赞列表
this.likeList = []
}
}
}, 5000)
},
//添加一个赞
addLike(option = {}) {
this.likeList.push(option)
//每次点击记录下最近的一次点击的时间
let currentTime = new Date().getTime() / 1000
this.setCache(this.likeTimeKey, currentTime)
},
/**
*
* @param {缓存key} key
* @param {需要存储的缓存值} value
* @param {过期时间} expire
*/
setCache(key, value, expire = 0) {
let obj = {
data: value, //存储的数据
time: Date.now() / 1000, //记录存储的时间戳
expire: expire //记录过期时间,单位秒
}
uni.setStorageSync(key, JSON.stringify(obj))
},
/**
*
* @param {缓存key} key
*/
getCache(key) {
let val = uni.getStorageSync(key)
if (!val) {
return null
}
val = JSON.parse(val)
if (val.expire && Date.now() / 1000 - val.time > val.expire) {
uni.removeStorageSync(key)
return null
}
return val.data
}
}
}
</script>
<style lang="scss" scoped>
.like-effect-wrap {
position: absolute;
//使用动画
animation: floatAnimation 4s 1 forwards;
//下落的动画
@keyframes floatAnimation {
0% {
transform: scale(0.8) rotate(-10deg);
opacity: 1;
}
100% {
transform: translateY(-500rpx) scale(1.6) rotate(10deg);
opacity: 0;
}
}
.like-image {
width: 100rpx;
}
}
</style>
二、使用
1.引入组件
import likeEffect from '../like-effect'
export default {
components: {
likeEffect
},
...
}
2.模板里面
<!-- 点赞特效 -->
<like-effect ref="likeEffect" />
<!-- 点赞特效 -->
3.方法使用
submitLike(event) {
//显示点赞特效
this.$refs.likeEffect.addLike({
left: event.detail.x, //位置X
top: event.detail.y //位置Y
})
}
网友评论