vue 实现点赞
实现点赞功能的基本思路
在Vue中实现点赞功能通常涉及前端交互与后端数据同步。核心逻辑包括:按钮状态切换、动画效果、数据持久化(如调用API更新数据库)。以下是具体实现方法:
基础实现(纯前端)
仅展示前端交互效果,不涉及后端数据存储:

<template>
<button
@click="toggleLike"
:class="{ 'liked': isLiked }"
>
{{ 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>
<style scoped>
.liked {
color: red;
font-weight: bold;
}
</style>
完整实现(前后端交互)
假设后端提供POST /api/like接口,需传递文章ID和用户ID:
<template>
<button
@click="handleLike"
:disabled="isLoading"
:class="{ 'liked': isLiked }"
>
<span v-if="isLoading">处理中...</span>
<span v-else>{{ isLiked ? '已赞' : '点赞' }} ({{ likeCount }})</span>
</button>
</template>
<script>
import axios from 'axios';
export default {
props: {
postId: {
type: String,
required: true
}
},
data() {
return {
isLiked: false,
likeCount: 0,
isLoading: false
}
},
async created() {
await this.fetchLikeStatus();
},
methods: {
async fetchLikeStatus() {
const res = await axios.get(`/api/like/status?postId=${this.postId}`);
this.isLiked = res.data.isLiked;
this.likeCount = res.data.count;
},
async handleLike() {
this.isLoading = true;
try {
await axios.post('/api/like', {
postId: this.postId,
action: this.isLiked ? 'unlike' : 'like'
});
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? 1 : -1;
} catch (error) {
console.error('操作失败:', error);
} finally {
this.isLoading = false;
}
}
}
}
</script>
添加动画效果
使用Vue的过渡动画增强用户体验:

<template>
<button @click="toggleLike">
<transition name="bounce">
<span v-if="isLiked" key="liked">❤️</span>
<span v-else key="unliked">♡</span>
</transition>
{{ likeCount }}
</button>
</template>
<style scoped>
.bounce-enter-active {
animation: bounce-in 0.5s;
}
@keyframes bounce-in {
0% { transform: scale(0.9); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
</style>
防抖优化
防止用户快速连续点击导致重复请求:
import _ from 'lodash';
export default {
methods: {
handleLike: _.debounce(async function() {
// 原有逻辑
}, 500)
}
}
本地存储记忆
使用localStorage记住用户操作状态:
export default {
data() {
return {
isLiked: localStorage.getItem(`like_${this.postId}`) === 'true'
}
},
methods: {
toggleLike() {
this.isLiked = !this.isLiked;
localStorage.setItem(`like_${this.postId}`, this.isLiked);
}
}
}
注意事项
- 后端接口需做幂等性处理,防止重复点赞
- 对于未登录用户,应禁用按钮并提示登录
- 敏感操作需在后端验证用户权限
- 高并发场景建议使用Redis计数
以上实现可根据实际需求组合使用,例如同时添加动画效果和前后端交互。






