当前位置:首页 > 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 中实现滚动中断通常涉及监听滚动事件,并在特定条件下阻止默认行为或停止滚动。以下是几种常见方法: 监听滚动事件并阻止默认行为 通过 @scroll 或 @whe…

vue实现sql操作

vue实现sql操作

在Vue中实现SQL操作通常需要结合后端服务或本地数据库技术,因为前端JavaScript无法直接连接SQL数据库。以下是几种常见的实现方式: 通过API与后端交互 Vue前端通过HTTP请求(如…

vue实现一个系统

vue实现一个系统

Vue 系统实现步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目: npm init vue@latest my-system 选择需要的配置(Router、Pinia 等)。…

vue中登陆实现逻辑

vue中登陆实现逻辑

Vue 中登录实现逻辑 前端实现逻辑 表单验证 使用 Vue 的表单验证库(如 VeeValidate)或自定义验证规则,确保用户输入的账号和密码符合要求。例如,检查邮箱格式、密码长度等。 发送登录…

vue实现菜单栏锚点

vue实现菜单栏锚点

实现锚点菜单的基本思路 在Vue中实现菜单栏锚点功能,主要涉及两个方面:创建可跳转的锚点位置,以及菜单项的点击滚动控制。通过监听滚动事件可以高亮当前可见区域的对应菜单项。 创建页面锚点位置 在需要跳…

vue实现a4打印模板

vue实现a4打印模板

使用Vue实现A4打印模板 在Vue中实现A4打印模板需要结合CSS的打印样式和Vue的模板渲染能力。以下是具体实现方法: 设置A4纸张尺寸 在CSS中定义A4纸张的标准尺寸(210mm × 29…