当前位置:首页 > VUE

vue实现点赞案例

2026-01-23 05:44:47VUE

Vue实现点赞功能

基础实现(无持久化)

创建Vue组件,使用v-on绑定点击事件和v-bind动态绑定样式:

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

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

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

带API交互的实现

添加axios请求与后端交互:

<script>
import axios from 'axios';

export default {
  props: ['postId'],
  data() {
    return {
      isLiked: false,
      likeCount: 0
    }
  },
  async created() {
    const res = await axios.get(`/api/posts/${this.postId}/likes`)
    this.isLiked = res.data.isLiked
    this.likeCount = res.data.count
  },
  methods: {
    async toggleLike() {
      try {
        const action = this.isLiked ? 'unlike' : 'like'
        await axios.post(`/api/posts/${this.postId}/${action}`)
        this.isLiked = !this.isLiked
        this.likeCount += this.isLiked ? 1 : -1
      } catch (error) {
        console.error('操作失败:', error)
      }
    }
  }
}
</script>

优化体验(防抖处理)

添加lodash防抖防止重复点击:

import { debounce } from 'lodash';

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

动画效果

添加过渡动画增强用户体验:

<template>
  <transition name="bounce">
    <span v-if="isLiked" class="heart">❤</span>
  </transition>
</template>

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

本地存储持久化

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

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

相关文章

vue组件实现

vue组件实现

Vue 组件实现基础 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。组件的实现包括定义、注册、数据传递和生命周期管理等。 定义组件 组件可以通过单文件组件(.…

vue实现同步

vue实现同步

Vue 实现同步的方法 在 Vue 中实现同步操作通常涉及数据绑定、状态管理和异步操作的处理。以下是几种常见的方法: 使用计算属性(Computed Properties) 计算属性基于响应式依赖进…

vue实现ajax

vue实现ajax

Vue 中实现 AJAX 的几种方法 在 Vue 中实现 AJAX 请求可以通过原生 JavaScript 的 XMLHttpRequest、第三方库如 axios 或 fetch API 来完成。以…

vue实现Siri

vue实现Siri

Vue 实现 Siri 风格语音交互 实现类似 Siri 的语音交互功能需要结合语音识别、语音合成和前端交互逻辑。Vue 作为前端框架,可以很好地管理这些功能的交互状态。 语音识别集成 使用 Web…

vue 实现遮罩

vue 实现遮罩

Vue 实现遮罩层的方法 使用固定定位和透明背景 在Vue中实现遮罩层可以通过CSS固定定位结合透明背景色完成。创建一个全屏遮罩组件,利用position: fixed覆盖整个视窗。 <tem…

vue ref实现

vue ref实现

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