当前位置:首页 > 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)
      }
    }
  }
})

优化用户体验

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

<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中实现无限滚动列表通常结合监听滚动事件和动态加载数据。以下是几种常见方法: 使用自定义指令 创建自定义指令v-infinite-scroll监听滚动事件: Vu…

vue中登陆实现逻辑

vue中登陆实现逻辑

Vue 中登录实现逻辑 前端实现逻辑 表单验证 使用 Vue 的表单验证库(如 VeeValidate)或自定义验证规则,确保用户输入的账号和密码符合要求。例如,检查邮箱格式、密码长度等。 发送登录…

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue实现分类

vue实现分类

Vue实现分类功能的方法 使用v-for和计算属性 通过计算属性对数据进行分类处理,结合v-for渲染分类后的列表。示例代码: <template> <div>…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model…

vue实现xss

vue实现xss

XSS 攻击简介 XSS(跨站脚本攻击)是一种常见的安全漏洞,攻击者通过注入恶意脚本到网页中,当其他用户访问该页面时,脚本会在其浏览器中执行,可能导致数据泄露或会话劫持。 Vue 中的 XSS…