当前位置:首页 > VUE

vue实现点赞案例

2026-02-23 20:22:29VUE

Vue 点赞功能实现

在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交互的实现

vue实现点赞案例

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 实现多层评论回复 数据结构设计 多层评论通常采用嵌套结构,每个评论对象包含子评论数组。示例数据结构如下: comments: [ { id: 1, content: '父…

vue 实现拖拽

vue 实现拖拽

Vue 实现拖拽功能 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。 <template> &l…

vue 实现href

vue 实现href

Vue 实现 href 的方法 在 Vue 中实现 href 功能可以通过多种方式,具体取决于需求场景。以下是几种常见的方法: 使用 <a> 标签 直接使用 HTML 的 <a&g…

vue实现portal

vue实现portal

Vue 实现 Portal 功能 Portal 是一种将子节点渲染到父组件 DOM 层级之外的 DOM 节点的技术,常用于实现模态框、弹出层等需要脱离当前组件层级的场景。Vue 可以通过多种方式实现…

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…

vue实现datalist

vue实现datalist

使用 Vue 实现 HTML5 的 datalist 功能 HTML5 的 <datalist> 元素提供了一种自动完成输入框的功能,允许用户在输入时从预定义的选项列表中选择。以下是几种在…