vue实现评论点赞
Vue 实现评论点赞功能
数据绑定与事件处理
在 Vue 中,可以通过 v-model 绑定点赞状态,使用 v-on 或 @ 监听点击事件。假设每条评论数据包含 id、content 和 liked 字段:
<template>
<div class="comment" v-for="comment in comments" :key="comment.id">
<p>{{ comment.content }}</p>
<button @click="toggleLike(comment)">
{{ comment.liked ? '取消点赞' : '点赞' }}
</button>
<span>点赞数: {{ comment.likes }}</span>
</div>
</template>
状态更新逻辑
在 Vue 实例的 methods 中定义 toggleLike 方法,更新点赞状态和计数:

<script>
export default {
data() {
return {
comments: [
{ id: 1, content: '评论1', liked: false, likes: 0 },
{ id: 2, content: '评论2', liked: true, likes: 5 }
]
}
},
methods: {
toggleLike(comment) {
comment.liked = !comment.liked;
comment.likes += comment.liked ? 1 : -1;
}
}
}
</script>
后端交互(可选)
如果需要持久化点赞数据,可以通过 axios 发送请求到后端 API:

methods: {
async toggleLike(comment) {
try {
const response = await axios.post('/api/like', {
commentId: comment.id,
action: comment.liked ? 'unlike' : 'like'
});
comment.likes = response.data.likes;
comment.liked = response.data.liked;
} catch (error) {
console.error('点赞失败:', error);
}
}
}
样式优化
为点赞按钮添加动态样式,反映当前状态:
<style>
button {
background: #fff;
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
}
button:hover {
background: #f0f0f0;
}
button.liked {
background: #1890ff;
color: white;
border-color: #1890ff;
}
</style>
完整组件示例
整合以上代码的完整单文件组件:
<template>
<div class="comment" v-for="comment in comments" :key="comment.id">
<p>{{ comment.content }}</p>
<button
@click="toggleLike(comment)"
:class="{ liked: comment.liked }"
>
{{ comment.liked ? '取消点赞' : '点赞' }}
</button>
<span>点赞数: {{ comment.likes }}</span>
</div>
</template>
<script>
export default {
data() {
return {
comments: [
{ id: 1, content: '评论1', liked: false, likes: 0 },
{ id: 2, content: '评论2', liked: true, likes: 5 }
]
}
},
methods: {
toggleLike(comment) {
comment.liked = !comment.liked;
comment.likes += comment.liked ? 1 : -1;
}
}
}
</script>
<style>
.comment {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #eee;
}
button {
background: #fff;
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
}
button:hover {
background: #f0f0f0;
}
button.liked {
background: #1890ff;
color: white;
border-color: #1890ff;
}
</style>






