当前位置:首页 > VUE

vue 实现点赞

2026-02-20 06:11:26VUE

实现点赞功能的基本思路

在Vue中实现点赞功能通常涉及前端交互与后端数据同步。核心逻辑包括:按钮状态切换、动画效果、数据持久化(如调用API更新数据库)。以下是具体实现方法:

基础实现(纯前端)

仅展示前端交互效果,不涉及后端数据存储:

<template>
  <button 
    @click="toggleLike" 
    :class="{ 'liked': isLiked }"
  >
    {{ isLiked ? '已赞' : '点赞' }} ({{ likeCount }})
  </button>
</template>

<script>
export default {
  data() {
    return {
      isLiked: false,
      likeCount: 0
    }
  },
  methods: {
    toggleLike() {
      this.isLiked = !this.isLiked;
      this.likeCount += this.isLiked ? 1 : -1;
    }
  }
}
</script>

<style scoped>
.liked {
  color: red;
  font-weight: bold;
}
</style>

完整实现(前后端交互)

假设后端提供POST /api/like接口,需传递文章ID和用户ID:

<template>
  <button 
    @click="handleLike" 
    :disabled="isLoading"
    :class="{ 'liked': isLiked }"
  >
    <span v-if="isLoading">处理中...</span>
    <span v-else>{{ isLiked ? '已赞' : '点赞' }} ({{ likeCount }})</span>
  </button>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    postId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      isLiked: false,
      likeCount: 0,
      isLoading: false
    }
  },
  async created() {
    await this.fetchLikeStatus();
  },
  methods: {
    async fetchLikeStatus() {
      const res = await axios.get(`/api/like/status?postId=${this.postId}`);
      this.isLiked = res.data.isLiked;
      this.likeCount = res.data.count;
    },
    async handleLike() {
      this.isLoading = true;
      try {
        await axios.post('/api/like', {
          postId: this.postId,
          action: this.isLiked ? 'unlike' : 'like'
        });
        this.isLiked = !this.isLiked;
        this.likeCount += this.isLiked ? 1 : -1;
      } catch (error) {
        console.error('操作失败:', error);
      } finally {
        this.isLoading = false;
      }
    }
  }
}
</script>

添加动画效果

使用Vue的过渡动画增强用户体验:

<template>
  <button @click="toggleLike">
    <transition name="bounce">
      <span v-if="isLiked" key="liked">❤️</span>
      <span v-else key="unliked">♡</span>
    </transition>
    {{ likeCount }}
  </button>
</template>

<style scoped>
.bounce-enter-active {
  animation: bounce-in 0.5s;
}
@keyframes bounce-in {
  0% { transform: scale(0.9); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}
</style>

防抖优化

防止用户快速连续点击导致重复请求:

import _ from 'lodash';

export default {
  methods: {
    handleLike: _.debounce(async function() {
      // 原有逻辑
    }, 500)
  }
}

本地存储记忆

使用localStorage记住用户操作状态:

vue 实现点赞

export default {
  data() {
    return {
      isLiked: localStorage.getItem(`like_${this.postId}`) === 'true'
    }
  },
  methods: {
    toggleLike() {
      this.isLiked = !this.isLiked;
      localStorage.setItem(`like_${this.postId}`, this.isLiked);
    }
  }
}

注意事项

  1. 后端接口需做幂等性处理,防止重复点赞
  2. 对于未登录用户,应禁用按钮并提示登录
  3. 敏感操作需在后端验证用户权限
  4. 高并发场景建议使用Redis计数

以上实现可根据实际需求组合使用,例如同时添加动画效果和前后端交互。

标签: vue
分享给朋友:

相关文章

vue查看更多怎么实现

vue查看更多怎么实现

实现 Vue 的“查看更多”功能 数据截取与显示控制 通过 v-if 或 v-show 控制内容的显示与隐藏。初始状态下只显示部分内容,点击“查看更多”后展开完整内容。 <template&g…

vue实现token

vue实现token

Vue 中实现 Token 认证的方法 在 Vue 中实现 Token 认证通常涉及前端与后端的交互,包括 Token 的获取、存储、发送和刷新等操作。以下是具体实现步骤: 获取 Token 用户登…

vue 实现搜索

vue 实现搜索

实现 Vue 搜索功能 在 Vue 中实现搜索功能通常涉及以下几个关键步骤: 数据绑定与输入监听 使用 v-model 双向绑定搜索输入框的值,监听用户输入: <template>…

vue ref实现

vue ref实现

Vue 中 ref 的实现 在 Vue 中,ref 是一个用于创建响应式引用的 API,适用于基本类型和对象。以下是 ref 的核心实现原理和使用方法。 基本实现原理 ref 通过 Reactive…

vue实现分站

vue实现分站

Vue 实现分站的方案 在 Vue 中实现分站功能通常涉及路由配置、环境变量管理和动态加载资源。以下是几种常见的实现方式: 基于路由的分站实现 通过 Vue Router 配置多路由,区分不同站点的…

vue实现项目

vue实现项目

Vue 项目实现指南 环境准备 确保已安装 Node.js(建议版本 14+)和 npm/yarn。通过以下命令检查版本: node -v npm -v 创建 Vue 项目 使用 Vue CLI 快…