vue点赞实现
实现点赞功能的基本思路
在Vue中实现点赞功能通常涉及前端交互与后端数据同步。核心逻辑包括点击事件处理、状态更新、UI反馈及API调用。
前端交互实现
模板部分
使用v-on或@click绑定点击事件,通过v-bind动态切换图标或文字样式:

<button @click="handleLike" :class="{ 'liked': isLiked }">
{{ isLiked ? '已赞' : '点赞' }}
</button>
脚本部分
定义数据状态和方法:
data() {
return {
isLiked: false,
likeCount: 0
}
},
methods: {
handleLike() {
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? 1 : -1;
// 调用API同步到后端
this.updateLikeStatus();
}
}
后端数据同步
通过Axios发送POST请求更新点赞状态:

async updateLikeStatus() {
try {
const response = await axios.post('/api/like', {
postId: this.postId,
isLiked: this.isLiked
});
console.log(response.data.message);
} catch (error) {
// 失败时回滚状态
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? -1 : 1;
}
}
优化用户体验
防抖处理
避免重复点击触发多次请求:
import { debounce } from 'lodash';
methods: {
handleLike: debounce(function() {
// 原有逻辑
}, 300)
}
动画效果
使用Vue过渡或CSS动画增强反馈:
button.liked {
transform: scale(1.1);
transition: all 0.3s ease;
}
完整组件示例
<template>
<div>
<button
@click="handleLike"
:class="{ 'liked': isLiked }"
class="like-button"
>
{{ isLiked ? '❤️ 已赞' : '🤍 点赞' }} ({{ likeCount }})
</button>
</div>
</template>
<script>
import axios from 'axios';
import { debounce } from 'lodash';
export default {
props: ['postId'],
data() {
return {
isLiked: false,
likeCount: 0
}
},
methods: {
handleLike: debounce(function() {
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? 1 : -1;
this.updateLikeStatus();
}, 300),
async updateLikeStatus() {
try {
await axios.post('/api/like', {
postId: this.postId,
isLiked: this.isLiked
});
} catch {
this.isLiked = !this.isLiked;
this.likeCount += this.isLiked ? -1 : 1;
}
}
},
created() {
// 初始化时获取当前点赞状态
axios.get(`/api/like-status?postId=${this.postId}`)
.then(response => {
this.isLiked = response.data.isLiked;
this.likeCount = response.data.count;
});
}
}
</script>
<style>
.like-button {
border: none;
background: transparent;
cursor: pointer;
font-size: 16px;
}
.liked {
color: #ff2d55;
}
</style>






