vue实现帖子点赞
实现帖子点赞功能
在Vue中实现帖子点赞功能,通常需要结合前端交互和后端数据存储。以下是具体实现方法:
前端组件实现
创建点赞按钮组件,使用Vue的响应式数据管理点赞状态:

<template>
<button @click="handleLike" :class="{ 'liked': isLiked }">
{{ likeCount }} {{ isLiked ? '已赞' : '点赞' }}
</button>
</template>
<script>
export default {
props: {
postId: Number,
initialLiked: Boolean,
initialLikeCount: Number
},
data() {
return {
isLiked: this.initialLiked,
likeCount: this.initialLikeCount
}
},
methods: {
async handleLike() {
try {
const response = await axios.post(`/api/posts/${this.postId}/like`)
this.isLiked = !this.isLiked
this.likeCount = this.isLiked ? this.likeCount + 1 : this.likeCount - 1
} catch (error) {
console.error('点赞操作失败', error)
}
}
}
}
</script>
<style scoped>
button {
background: #fff;
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
}
.liked {
background: #1890ff;
color: white;
}
</style>
后端API接口
Node.js示例实现点赞API接口:
// Express路由
router.post('/posts/:id/like', async (req, res) => {
try {
const postId = req.params.id
const userId = req.user.id // 从认证中获取用户ID
// 检查用户是否已点赞
const existingLike = await Like.findOne({
where: { postId, userId }
})
if (existingLike) {
// 取消点赞
await existingLike.destroy()
await Post.decrement('likeCount', { where: { id: postId } })
return res.json({ liked: false })
} else {
// 添加点赞
await Like.create({ postId, userId })
await Post.increment('likeCount', { where: { id: postId } })
return res.json({ liked: true })
}
} catch (error) {
res.status(500).json({ error: '操作失败' })
}
})
数据库设计
MySQL关系表结构设计:

CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT,
like_count INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE likes (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE KEY (post_id, user_id)
);
优化点赞体验
实现即时反馈的优化方案:
// 在组件中添加防抖处理
methods: {
handleLike: _.debounce(async function() {
const action = this.isLiked ? 'unlike' : 'like'
this.isLiked = !this.isLiked
this.likeCount = this.isLiked ? this.likeCount + 1 : this.likeCount - 1
try {
await axios.post(`/api/posts/${this.postId}/${action}`)
} catch (error) {
// 回滚UI状态
this.isLiked = !this.isLiked
this.likeCount = this.isLiked ? this.likeCount + 1 : this.likeCount - 1
alert('操作失败,请重试')
}
}, 300)
}
用户界面状态管理
使用Vuex管理全局点赞状态:
// store/modules/posts.js
const actions = {
async toggleLike({ commit }, postId) {
commit('TOGGLE_LIKE', postId)
try {
await api.toggleLike(postId)
} catch (error) {
commit('TOGGLE_LIKE', postId) // 出错时回滚
}
}
}
const mutations = {
TOGGLE_LIKE(state, postId) {
const post = state.posts.find(p => p.id === postId)
if (post) {
post.isLiked = !post.isLiked
post.likeCount += post.isLiked ? 1 : -1
}
}
}
以上方案实现了完整的点赞功能,包括前端交互、后端API、数据库设计以及状态管理优化。






