点赞功能实现vue
点赞功能实现(Vue)
在Vue中实现点赞功能,通常需要结合前端交互和后端数据存储。以下是两种常见实现方式:

纯前端实现(无持久化)
适用于无需保存点赞状态的场景,如临时交互。
<template>
<button @click="toggleLike">
{{ isLiked ? '取消点赞' : '点赞' }} ({{ likeCount }})
</button>
</template>
<script>
export default {
data() {
return {
isLiked: false,
likeCount: 42
}
},
methods: {
toggleLike() {
this.isLiked = !this.isLiked
this.likeCount += this.isLiked ? 1 : -1
}
}
}
</script>
前后端交互实现
需要配合后端API实现持久化存储。
<template>
<button @click="handleLike" :disabled="loading">
{{ data.is_liked ? '取消点赞' : '点赞' }} ({{ data.like_count }})
</button>
</template>
<script>
import axios from 'axios'
export default {
props: ['postId'],
data() {
return {
loading: false,
data: {
is_liked: false,
like_count: 0
}
}
},
created() {
this.fetchLikeStatus()
},
methods: {
async fetchLikeStatus() {
const res = await axios.get(`/api/posts/${this.postId}/likes`)
this.data = res.data
},
async handleLike() {
this.loading = true
try {
const action = this.data.is_liked ? 'delete' : 'post'
await axios[action](`/api/posts/${this.postId}/likes`)
this.data.is_liked = !this.data.is_liked
this.data.like_count += this.data.is_liked ? 1 : -1
} finally {
this.loading = false
}
}
}
}
</script>
优化建议
- 添加防抖处理防止快速重复点击
- 使用Vuex管理全局点赞状态
- 添加动画效果提升用户体验
- 考虑实现本地缓存减少API请求
后端接口示例
// Express.js示例
router.post('/posts/:id/likes', auth, async (req, res) => {
const post = await Post.findByPk(req.params.id)
await post.addLike(req.user.id)
res.json({ is_liked: true, like_count: post.likeCount })
})
router.delete('/posts/:id/likes', auth, async (req, res) => {
const post = await Post.findByPk(req.params.id)
await post.removeLike(req.user.id)
res.json({ is_liked: false, like_count: post.likeCount })
})
实现时需根据具体业务需求调整逻辑,如限制用户点赞次数、防止刷赞等。







