当前位置:首页 > VUE

vue实现列表点赞

2026-02-20 16:55:25VUE

实现思路

在Vue中实现列表点赞功能,主要涉及数据绑定、事件处理和状态更新。通常需要为列表中的每一项维护一个点赞状态,并通过点击事件触发状态变更。

基础实现

准备一个包含点赞状态的列表数据,使用v-for渲染列表,并为每个项绑定点击事件。

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item.content }}
        <button @click="toggleLike(index)">
          {{ item.liked ? '取消点赞' : '点赞' }} ({{ item.likes }})
        </button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { content: '内容1', likes: 10, liked: false },
        { content: '内容2', likes: 5, liked: true },
        { content: '内容3', likes: 8, liked: false }
      ]
    }
  },
  methods: {
    toggleLike(index) {
      const item = this.items[index]
      item.liked = !item.liked
      item.likes += item.liked ? 1 : -1
    }
  }
}
</script>

优化实现

添加动画效果提升用户体验,使用Vue的过渡组件实现点赞动画。

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item.content }}
        <button @click="toggleLike(index)">
          <transition name="fade" mode="out-in">
            <span :key="item.liked">
              {{ item.liked ? '取消点赞' : '点赞' }}
            </span>
          </transition>
          ({{ item.likes }})
        </button>
      </li>
    </ul>
  </div>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

服务端交互

实际项目中通常需要与后端API交互,保存点赞状态到数据库。

methods: {
  async toggleLike(index) {
    const item = this.items[index]
    const newLikedState = !item.liked

    try {
      const response = await axios.post('/api/like', {
        itemId: item.id,
        liked: newLikedState
      })

      item.liked = newLikedState
      item.likes = response.data.likes
    } catch (error) {
      console.error('点赞操作失败', error)
    }
  }
}

防抖处理

为防止用户快速多次点击,可以添加防抖功能。

import { debounce } from 'lodash'

methods: {
  toggleLike: debounce(function(index) {
    const item = this.items[index]
    item.liked = !item.liked
    item.likes += item.liked ? 1 : -1
  }, 300)
}

vue实现列表点赞

标签: 列表vue
分享给朋友:

相关文章

vue实现文档分享

vue实现文档分享

Vue 实现文档分享功能 文档分享功能通常涉及文件上传、存储、生成分享链接以及权限控制等模块。以下是基于 Vue 的实现方案: 文件上传组件 使用 element-ui 或 ant-design-…

vue实现store

vue实现store

Vue 实现 Store 在 Vue 中,可以通过 Vuex 或 Pinia 实现全局状态管理(Store)。以下是两种主流方案的实现方法。 使用 Vuex 实现 Store Vuex 是 Vu…

vue实现主题

vue实现主题

Vue 实现主题的方法 使用 CSS 变量动态切换主题 定义全局 CSS 变量,通过修改这些变量实现主题切换。在 Vue 的根组件或全局样式中定义变量: :root { --primary-c…

vue广告实现

vue广告实现

Vue 广告实现方法 在 Vue 项目中实现广告功能可以通过多种方式完成,具体取决于广告类型和需求。以下是几种常见的实现方法: 使用第三方广告平台 许多广告平台如 Google AdSense…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutati…

vue实现selectable

vue实现selectable

Vue 实现可选择的 Select 组件 在 Vue 中实现一个可选择的 Select 组件,可以通过以下几种方式: 使用原生 HTML select 元素 <template>…