vue实现点赞功能
实现点赞功能的基本思路
在Vue中实现点赞功能通常涉及前端交互与后端数据同步。核心逻辑包括:点击按钮切换状态、更新UI、发送请求到后端保存数据。
前端实现步骤
模板部分
<template>
<button @click="handleLike" :class="{ 'liked': isLiked }">
{{ isLiked ? '已赞' : '点赞' }} ({{ likeCount }})
</button>
</template>
脚本部分

<script>
export default {
data() {
return {
isLiked: false, // 当前用户是否点赞
likeCount: 0 // 总点赞数
}
},
methods: {
handleLike() {
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? 1 : -1;
// 发送API请求到后端
axios.post('/api/like', {
action: this.isLiked ? 'like' : 'unlike'
}).catch(error => {
// 失败时回滚状态
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? -1 : 1;
});
}
}
}
</script>
样式部分
<style scoped>
button {
padding: 8px 16px;
background: #f0f0f0;
border: none;
border-radius: 4px;
cursor: pointer;
}
.liked {
background: #1890ff;
color: white;
}
</style>
后端交互注意事项
- 使用防抖避免重复提交(如lodash的
_.debounce) - 重要操作需在后端验证用户权限
- 考虑使用乐观更新(先更新UI再确认请求成功)
高级优化方案
本地存储记录点赞状态

// 防止页面刷新后状态丢失
localStorage.setItem('liked_post_123', true);
动画效果增强体验
.liked {
transition: all 0.3s ease;
transform: scale(1.1);
}
服务端渲染(SSR)兼容
需在created钩子中初始化状态:
created() {
if (process.server) {
this.isLiked = this.$ssrContext.userLikedStatus || false;
}
}
完整组件示例
<template>
<button
@click="debouncedLike"
:class="['like-btn', { 'liked': isLiked }]"
:disabled="isLoading"
>
<span v-if="!isLoading">
{{ isLiked ? '❤️ 已赞' : '🤍 点赞' }} ({{ likeCount }})
</span>
<span v-else>加载中...</span>
</button>
</template>
<script>
import { debounce } from 'lodash';
export default {
props: {
initialLiked: Boolean,
initialCount: Number,
postId: String
},
data() {
return {
isLiked: this.initialLiked,
likeCount: this.initialCount,
isLoading: false
};
},
created() {
this.debouncedLike = debounce(this.handleLike, 300);
},
methods: {
async handleLike() {
this.isLoading = true;
try {
const action = this.isLiked ? 'unlike' : 'like';
await axios.post(`/posts/${this.postId}/like`, { action });
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? 1 : -1;
localStorage.setItem(`liked_${this.postId}`, this.isLiked);
} catch (error) {
console.error('点赞操作失败', error);
} finally {
this.isLoading = false;
}
}
}
};
</script>






