vue实现点击关注
实现点击关注功能
在Vue中实现点击关注功能,通常需要处理用户交互、状态管理和API请求。以下是实现步骤:
数据绑定与状态管理
在Vue组件中定义一个布尔值数据属性表示关注状态:
data() {
return {
isFollowing: false
}
}
模板中的交互绑定
使用v-on指令绑定点击事件,并根据状态显示不同文本:
<button @click="toggleFollow">
{{ isFollowing ? '已关注' : '关注' }}
</button>
事件处理方法
在methods中定义toggleFollow方法处理点击逻辑:
methods: {
toggleFollow() {
this.isFollowing = !this.isFollowing
// 这里可以添加API调用
}
}
添加API请求
实际应用中需要调用后端接口:
async toggleFollow() {
try {
const action = this.isFollowing ? 'unfollow' : 'follow'
const response = await axios.post(`/api/${action}`, {userId: this.targetUserId})
if (response.data.success) {
this.isFollowing = !this.isFollowing
}
} catch (error) {
console.error('操作失败', error)
}
}
样式优化
根据状态添加不同样式类:
<button
@click="toggleFollow"
:class="{'follow-btn': true, 'following': isFollowing}"
>
{{ isFollowing ? '已关注' : '关注' }}
</button>
.follow-btn {
padding: 5px 15px;
border-radius: 4px;
cursor: pointer;
}
.following {
background-color: #f0f0f0;
color: #666;
}
初始状态获取
在created钩子中获取初始关注状态:
async created() {
try {
const response = await axios.get(`/api/check-follow?userId=${this.targetUserId}`)
this.isFollowing = response.data.isFollowing
} catch (error) {
console.error('获取关注状态失败', error)
}
}
防抖处理
避免快速重复点击:
import { debounce } from 'lodash'
methods: {
toggleFollow: debounce(function() {
// 原有逻辑
}, 300)
}






