vue实现点击关注
Vue 实现点击关注功能
在 Vue 中实现点击关注功能通常涉及以下几个步骤:
数据绑定与事件处理
使用 v-model 或 :class 绑定关注状态,通过 @click 触发关注/取消关注操作。
<template>
<button
:class="{ 'active': isFollowing }"
@click="toggleFollow"
>
{{ isFollowing ? '已关注' : '关注' }}
</button>
</template>
<script>
export default {
data() {
return {
isFollowing: false
}
},
methods: {
toggleFollow() {
this.isFollowing = !this.isFollowing
// 这里可以添加API调用
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
与后端API交互
通常需要调用后端接口更新关注状态,使用 axios 或 fetch。
methods: {
async toggleFollow() {
try {
const action = this.isFollowing ? 'unfollow' : 'follow'
const response = await axios.post(`/api/${action}`, {
userId: this.targetUserId
})
this.isFollowing = !this.isFollowing
} catch (error) {
console.error('操作失败:', error)
}
}
}
状态持久化
通过 Vuex 或 Pinia 管理全局关注状态,避免页面刷新后状态丢失。
// Pinia 示例
import { defineStore } from 'pinia'
export const useFollowStore = defineStore('follow', {
state: () => ({
followingList: []
}),
actions: {
async toggleFollow(userId) {
if (this.followingList.includes(userId)) {
await axios.post('/api/unfollow', { userId })
this.followingList = this.followingList.filter(id => id !== userId)
} else {
await axios.post('/api/follow', { userId })
this.followingList.push(userId)
}
}
}
})
优化用户体验
添加加载状态和操作反馈,提升交互体验。
<template>
<button
:disabled="isLoading"
@click="toggleFollow"
>
<span v-if="isLoading">处理中...</span>
<span v-else>{{ isFollowing ? '已关注' : '关注' }}</span>
</button>
</template>
<script>
export default {
data() {
return {
isLoading: false
}
},
methods: {
async toggleFollow() {
this.isLoading = true
try {
await this.$store.dispatch('toggleFollow', this.userId)
} finally {
this.isLoading = false
}
}
}
}
</script>
注意事项
- 对于未登录用户,点击关注时应跳转到登录页面
- 考虑添加防抖处理避免快速重复点击
- 移动端适配可能需要调整按钮样式
- 关注成功后可以触发通知或更新相关数据列表







