当前位置:首页 > 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请求与后端交互:

vue实现点赞案例

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

动画效果

vue实现点赞案例

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

<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记住用户点赞状态:

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 提供了 v-for 指令用于实现循环渲染列表数据。v-for 可以遍历数组、对象或数字范围,生成动态的 DOM 元素。 遍历数组 使用 v-for 遍历数组时,语法为…

vue实现全屏

vue实现全屏

Vue 实现全屏功能的方法 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 来实现。以下是几种常见的实现方式: 使用原生 Fullscreen API 通过调用 doc…

tabbar 实现 vue

tabbar 实现 vue

在 Vue 中实现 TabBar 功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue Router 结合自定义组件 创建一个自定义的 TabBar 组件,结合 Vue Router 实现…

vue实现Siri

vue实现Siri

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

vue实现尺子

vue实现尺子

Vue 实现尺子组件 实现一个尺子组件可以通过 Canvas 或纯 CSS 完成。以下是两种常见实现方式: 使用 Canvas 绘制尺子 通过 Canvas 动态绘制刻度线和数字,适合需要高精度或动…

vue实现导航

vue实现导航

使用 Vue Router 实现导航 Vue Router 是 Vue.js 官方提供的路由管理器,用于构建单页应用(SPA)的导航系统。以下是实现导航的基本步骤。 安装 Vue Router n…