当前位置:首页 > 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记住用户点赞状态:

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 实现简单弹窗 组件基础结构 创建一个名为 Modal.vue 的组件文件,包含模板、脚本和样式部分: <template> <div class="mod…

vue实现字母添加排序

vue实现字母添加排序

实现字母添加排序的方法 在Vue中实现字母添加排序功能,可以通过以下步骤完成: 创建Vue实例并定义数据 new Vue({ el: '#app', data: { lette…

vue实现上移下移插件

vue实现上移下移插件

实现上移下移功能的 Vue 插件 在 Vue 中实现列表项的上移和下移功能,可以通过自定义指令或组件封装的方式完成。以下是两种常见实现方式: 基于数组操作的通用方法 通过操作数组索引实现元素位置交…

vue实现右下角弹框

vue实现右下角弹框

实现右下角弹框的基本思路 在Vue中实现右下角弹框,通常需要结合CSS定位和Vue的组件化特性。弹框可以通过绝对定位固定在右下角,并通过Vue控制其显示与隐藏。 创建弹框组件 新建一个Vue组件(…

vue菜单实现

vue菜单实现

Vue 菜单实现方法 使用 Element UI 的菜单组件 Element UI 提供了现成的菜单组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用 el-menu 相关组件。…

vue实现xss

vue实现xss

XSS 攻击简介 XSS(跨站脚本攻击)是一种常见的安全漏洞,攻击者通过注入恶意脚本到网页中,当其他用户访问该页面时,脚本会在其浏览器中执行,可能导致数据泄露或会话劫持。 Vue 中的 XSS…