vue实现点赞案例
Vue实现点赞功能
基础实现(无持久化)
创建Vue组件,使用v-on绑定点击事件和v-bind动态绑定样式:
<template>
<button
@click="toggleLike"
:class="{ 'liked': isLiked }"
>
{{ 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>
<style scoped>
.liked {
color: red;
font-weight: bold;
}
</style>
带API交互的实现
添加axios请求与后端交互:
<script>
import axios from 'axios';
export default {
props: ['postId'],
data() {
return {
isLiked: false,
likeCount: 0
}
},
async created() {
const res = await axios.get(`/api/posts/${this.postId}/likes`)
this.isLiked = res.data.isLiked
this.likeCount = res.data.count
},
methods: {
async toggleLike() {
try {
const action = this.isLiked ? 'unlike' : 'like'
await axios.post(`/api/posts/${this.postId}/${action}`)
this.isLiked = !this.isLiked
this.likeCount += this.isLiked ? 1 : -1
} catch (error) {
console.error('操作失败:', error)
}
}
}
}
</script>
优化体验(防抖处理)
添加lodash防抖防止重复点击:
import { debounce } from 'lodash';
export default {
methods: {
toggleLike: debounce(async function() {
// 原有逻辑
}, 500)
}
}
动画效果
添加过渡动画增强用户体验:
<template>
<transition name="bounce">
<span v-if="isLiked" class="heart">❤</span>
</transition>
</template>
<style scoped>
.bounce-enter-active {
animation: bounce-in 0.5s;
}
@keyframes bounce-in {
0% { transform: scale(0); }
50% { transform: scale(1.5); }
100% { transform: scale(1); }
}
</style>
本地存储持久化
使用localStorage记住用户点赞状态:
export default {
data() {
return {
isLiked: localStorage.getItem(`like_${this.postId}`) === 'true'
}
},
methods: {
toggleLike() {
this.isLiked = !this.isLiked
localStorage.setItem(`like_${this.postId}`, this.isLiked)
}
}
}






