当前位置:首页 > VUE

vue实现点赞案例

2026-02-23 20:22:29VUE

Vue 点赞功能实现

在Vue中实现点赞功能可以通过数据绑定和事件处理来完成。以下是几种常见的实现方式:

基础实现

<template>
  <button @click="toggleLike">
    {{ 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>

带动画效果的实现

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

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

与后端API交互的实现

methods: {
  async toggleLike() {
    try {
      const response = await axios.post('/api/like', {
        postId: this.postId,
        action: this.isLiked ? 'unlike' : 'like'
      })
      this.isLiked = !this.isLiked
      this.likeCount = response.data.likeCount
    } catch (error) {
      console.error('点赞操作失败', error)
    }
  }
}

使用Vuex管理点赞状态

// store.js
state: {
  likedPosts: []
},
mutations: {
  TOGGLE_LIKE(state, postId) {
    const index = state.likedPosts.indexOf(postId)
    if (index === -1) {
      state.likedPosts.push(postId)
    } else {
      state.likedPosts.splice(index, 1)
    }
  }
}

// 组件中
computed: {
  isLiked() {
    return this.$store.state.likedPosts.includes(this.postId)
  }
},
methods: {
  toggleLike() {
    this.$store.commit('TOGGLE_LIKE', this.postId)
  }
}

防抖处理防止重复点击

import { debounce } from 'lodash'

methods: {
  toggleLike: debounce(function() {
    // 点赞逻辑
  }, 500)
}

这些实现方式可以根据具体需求进行组合和调整,满足不同场景下的点赞功能需求。

vue实现点赞案例

标签: 案例vue
分享给朋友:

相关文章

vue实现粘贴

vue实现粘贴

Vue 实现粘贴功能的方法 在 Vue 中实现粘贴功能通常涉及监听粘贴事件并处理剪贴板数据。以下是几种常见的实现方式: 监听原生粘贴事件 通过 @paste 指令或原生 addEventListen…

vue实现fullpage

vue实现fullpage

Vue 实现 FullPage 效果 在 Vue 中实现全屏滚动(FullPage)效果可以通过多种方式完成,以下是几种常见的方法: 使用现有库 vue-fullpage.js 安装 vue-fu…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue实现分栏

vue实现分栏

Vue实现分栏的常见方法 使用CSS Flexbox布局 通过Flexbox可以快速实现分栏效果,适合大多数响应式布局场景 <template> <div class="co…

vue拼图实现

vue拼图实现

实现 Vue 拼图游戏的方法 使用 Vue 组件和动态数据绑定 创建一个 Vue 组件来管理拼图的状态和逻辑。通过 v-for 动态渲染拼图块,利用 v-bind 绑定样式和位置。拼图块的数据可以存储…

vue实现github

vue实现github

Vue 实现 GitHub 相关功能 创建 GitHub API 请求 在 Vue 项目中,可以使用 axios 或 fetch 与 GitHub API 进行交互。需要在 GitHub 上创建个人访…