当前位置:首页 > VUE

vue实现帖子点赞

2026-02-24 12:48:16VUE

实现帖子点赞功能

在Vue中实现帖子点赞功能,通常需要结合前端交互和后端数据存储。以下是具体实现方法:

前端组件实现

创建点赞按钮组件,使用Vue的响应式数据管理点赞状态:

vue实现帖子点赞

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

<script>
export default {
  props: {
    postId: Number,
    initialLiked: Boolean,
    initialLikeCount: Number
  },
  data() {
    return {
      isLiked: this.initialLiked,
      likeCount: this.initialLikeCount
    }
  },
  methods: {
    async handleLike() {
      try {
        const response = await axios.post(`/api/posts/${this.postId}/like`)
        this.isLiked = !this.isLiked
        this.likeCount = this.isLiked ? this.likeCount + 1 : this.likeCount - 1
      } catch (error) {
        console.error('点赞操作失败', error)
      }
    }
  }
}
</script>

<style scoped>
button {
  background: #fff;
  border: 1px solid #ccc;
  padding: 5px 10px;
  cursor: pointer;
}

.liked {
  background: #1890ff;
  color: white;
}
</style>

后端API接口

Node.js示例实现点赞API接口:

// Express路由
router.post('/posts/:id/like', async (req, res) => {
  try {
    const postId = req.params.id
    const userId = req.user.id // 从认证中获取用户ID

    // 检查用户是否已点赞
    const existingLike = await Like.findOne({ 
      where: { postId, userId }
    })

    if (existingLike) {
      // 取消点赞
      await existingLike.destroy()
      await Post.decrement('likeCount', { where: { id: postId } })
      return res.json({ liked: false })
    } else {
      // 添加点赞
      await Like.create({ postId, userId })
      await Post.increment('likeCount', { where: { id: postId } })
      return res.json({ liked: true })
    }
  } catch (error) {
    res.status(500).json({ error: '操作失败' })
  }
})

数据库设计

MySQL关系表结构设计:

vue实现帖子点赞

CREATE TABLE posts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  content TEXT,
  like_count INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE likes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  post_id INT NOT NULL,
  user_id INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  UNIQUE KEY (post_id, user_id)
);

优化点赞体验

实现即时反馈的优化方案:

// 在组件中添加防抖处理
methods: {
  handleLike: _.debounce(async function() {
    const action = this.isLiked ? 'unlike' : 'like'
    this.isLiked = !this.isLiked
    this.likeCount = this.isLiked ? this.likeCount + 1 : this.likeCount - 1

    try {
      await axios.post(`/api/posts/${this.postId}/${action}`)
    } catch (error) {
      // 回滚UI状态
      this.isLiked = !this.isLiked
      this.likeCount = this.isLiked ? this.likeCount + 1 : this.likeCount - 1
      alert('操作失败,请重试')
    }
  }, 300)
}

用户界面状态管理

使用Vuex管理全局点赞状态:

// store/modules/posts.js
const actions = {
  async toggleLike({ commit }, postId) {
    commit('TOGGLE_LIKE', postId)
    try {
      await api.toggleLike(postId)
    } catch (error) {
      commit('TOGGLE_LIKE', postId) // 出错时回滚
    }
  }
}

const mutations = {
  TOGGLE_LIKE(state, postId) {
    const post = state.posts.find(p => p.id === postId)
    if (post) {
      post.isLiked = !post.isLiked
      post.likeCount += post.isLiked ? 1 : -1
    }
  }
}

以上方案实现了完整的点赞功能,包括前端交互、后端API、数据库设计以及状态管理优化。

标签: 帖子vue
分享给朋友:

相关文章

实现vue

实现vue

安装Vue.js 通过npm安装Vue.js是最常见的方式。确保已安装Node.js和npm,运行以下命令: npm install vue 或者使用CDN直接引入: <script src…

vue广告实现

vue广告实现

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

vue element实现

vue element实现

Vue Element UI 实现 Vue Element UI 是基于 Vue.js 的组件库,提供丰富的 UI 组件,适合快速开发企业级中后台产品。以下是一些关键实现方法和步骤: 安装 Vue…

vue实现公告

vue实现公告

Vue 实现公告功能的方法 公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式: 使用 marquee 标签实现滚动公告 <template> <…

vue实现rtc

vue实现rtc

Vue 实现 RTC 的步骤 安装依赖 在 Vue 项目中安装 WebRTC 相关依赖,如 simple-peer 或 peerjs,用于简化 WebRTC 的实现。 运行以下命令安装 simple-…

vue实现剪辑

vue实现剪辑

Vue 实现视频剪辑功能 在Vue中实现视频剪辑功能通常需要结合HTML5的<video>元素和第三方库(如FFmpeg.js或Video.js)。以下是几种常见的实现方法: 使用FF…