当前位置:首页 > VUE

vue实现点击关注

2026-02-18 23:03:03VUE

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交互

通常需要调用后端接口更新关注状态,使用 axiosfetch

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)
      }
    }
  }
})

优化用户体验

添加加载状态和操作反馈,提升交互体验。

vue实现点击关注

<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>

注意事项

  • 对于未登录用户,点击关注时应跳转到登录页面
  • 考虑添加防抖处理避免快速重复点击
  • 移动端适配可能需要调整按钮样式
  • 关注成功后可以触发通知或更新相关数据列表

标签: vue
分享给朋友:

相关文章

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…

vue实现popper

vue实现popper

Vue 实现 Popper 的方法 使用 Tippy.js 库 Tippy.js 是一个轻量级的 Popper.js 封装库,提供丰富的工具提示功能。安装 Tippy.js 及其 Vue 封装: n…

vue实现滚屏

vue实现滚屏

实现滚屏的基本方法 在Vue中实现滚屏效果可以通过多种方式完成,常见的有原生JavaScript滚动方法、第三方库或CSS动画。以下是几种常见实现方式: 使用window.scrollTo或Elem…

vue实现数据

vue实现数据

Vue 实现数据绑定的方法 Vue.js 提供了多种方式实现数据绑定,包括双向绑定、单向绑定以及动态数据绑定。以下是几种常见的实现方式: 双向数据绑定(v-model) 双向数据绑定通常用于表单元素…

vue实现banner

vue实现banner

Vue实现Banner轮播 使用Vue实现Banner轮播可以通过第三方库如swiper或vue-awesome-swiper,也可以手动实现基础轮播效果。以下是两种常见方法: 使用vue-awes…

vue框架实现CRM

vue框架实现CRM

Vue框架实现CRM系统 使用Vue框架构建CRM(客户关系管理)系统需要结合前端技术栈和后端API。以下为关键实现方法: 技术选型 核心框架:Vue 3(Composition API)…