vue实现点赞案例
Vue 点赞功能实现
在Vue中实现点赞功能可以通过数据绑定和事件处理来完成。以下是几种常见的实现方式:
基础实现
<template>
<button @click="toggleLike">
{{ isLiked ? '取消点赞' : '点赞' }} ({{ likeCount }})
</button>
</template>
<script>
export default {
data() {
return {
isLiked: false,
likeCount: 0
}
},
methods: {
toggleLike() {
this.isLiked = !this.isLiked
this.likeCount += this.isLiked ? 1 : -1
}
}
}
</script>
带动画效果的实现
<template>
<button @click="toggleLike" class="like-btn">
<transition name="bounce">
<span v-if="isLiked" key="liked">❤️</span>
<span v-else key="unliked">♡</span>
</transition>
{{ likeCount }}
</button>
</template>
<style>
.bounce-enter-active {
animation: bounce-in 0.5s;
}
@keyframes bounce-in {
0% { transform: scale(1); }
50% { transform: scale(1.5); }
100% { transform: scale(1); }
}
</style>
与后端API交互的实现
methods: {
async toggleLike() {
try {
const response = await axios.post('/api/like', {
postId: this.postId,
action: this.isLiked ? 'unlike' : 'like'
})
this.isLiked = !this.isLiked
this.likeCount = response.data.likeCount
} catch (error) {
console.error('点赞操作失败', error)
}
}
}
使用Vuex管理点赞状态
// store.js
state: {
likedPosts: []
},
mutations: {
TOGGLE_LIKE(state, postId) {
const index = state.likedPosts.indexOf(postId)
if (index === -1) {
state.likedPosts.push(postId)
} else {
state.likedPosts.splice(index, 1)
}
}
}
// 组件中
computed: {
isLiked() {
return this.$store.state.likedPosts.includes(this.postId)
}
},
methods: {
toggleLike() {
this.$store.commit('TOGGLE_LIKE', this.postId)
}
}
防抖处理防止重复点击
import { debounce } from 'lodash'
methods: {
toggleLike: debounce(function() {
// 点赞逻辑
}, 500)
}
这些实现方式可以根据具体需求进行组合和调整,满足不同场景下的点赞功能需求。







