vue实现列表点赞
实现思路
在Vue中实现列表点赞功能,需要结合数据绑定和事件处理。通过v-for渲染列表,为每个列表项绑定点赞状态和点击事件。点击时更新对应项的数据状态,并可选地发送请求到后端保存数据。

基础实现代码
<template>
<div>
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item.content }}
<button @click="toggleLike(index)">
{{ item.liked ? '取消点赞' : '点赞' }} ({{ item.likeCount }})
</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ content: '内容1', liked: false, likeCount: 0 },
{ content: '内容2', liked: false, likeCount: 0 },
{ content: '内容3', liked: false, likeCount: 0 }
]
}
},
methods: {
toggleLike(index) {
const item = this.list[index]
item.liked = !item.liked
item.likeCount += item.liked ? 1 : -1
}
}
}
</script>
进阶优化
加入后端交互和状态持久化,使用axios发送请求:

methods: {
async toggleLike(index) {
const item = this.list[index]
const newStatus = !item.liked
try {
const response = await axios.post('/api/like', {
id: item.id,
liked: newStatus
})
item.liked = newStatus
item.likeCount = response.data.likeCount
} catch (error) {
console.error('点赞操作失败', error)
}
}
}
样式优化
为点赞按钮添加视觉效果:
button {
background: none;
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
transition: all 0.3s;
}
button:hover {
background: #f0f0f0;
}
.liked {
color: red;
border-color: red;
}
在模板中动态绑定类名:
<button
@click="toggleLike(index)"
:class="{ liked: item.liked }"
>
{{ item.liked ? '取消点赞' : '点赞' }} ({{ item.likeCount }})
</button>
注意事项
- 对于大型列表,建议使用唯一ID而非索引作为
key - 考虑添加防抖处理防止快速重复点击
- 对于未登录用户,应禁用点赞按钮并提示登录
- 可添加加载状态防止重复提交






