当前位置:首页 > VUE

vue实现帖子点赞

2026-02-24 12:48:16VUE

实现帖子点赞功能

在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关系表结构设计:

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管理全局点赞状态:

vue实现帖子点赞

// 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 实现动画的方法 Vue 提供了多种方式来实现动画效果,包括内置的过渡系统、第三方动画库以及直接操作 CSS 或 JavaScript 动画。 使用 Vue 内置过渡系统 Vue 的 <…

vue实现 treegrid

vue实现 treegrid

Vue 实现 TreeGrid 的方法 使用现成组件库 Element UI、Ant Design Vue 等流行组件库提供了现成的 TreeTable/TreeGrid 组件,可直接使用。 Ele…

vue实现listview

vue实现listview

Vue 实现 ListView 的方法 基础列表渲染 使用 v-for 指令可以轻松实现基础列表渲染。在 Vue 中,v-for 用于遍历数组或对象,生成动态列表。 <template>…

vue实现分站

vue实现分站

Vue 实现分站的方案 在 Vue 中实现分站功能通常涉及路由配置、环境变量管理和动态加载资源。以下是几种常见的实现方式: 基于路由的分站实现 通过 Vue Router 配置多路由,区分不同站点的…

vue源码实现

vue源码实现

Vue 源码实现解析 Vue.js 的核心实现可以分为响应式系统、虚拟 DOM、模板编译、组件化等几个关键部分。以下是对这些核心机制的详细解析。 响应式系统 Vue 的响应式系统基于 Object.…

vue日历实现

vue日历实现

实现基础日历布局 使用Vue的模板语法构建日历的基本HTML结构。一个典型的日历包含星期标题和日期格子,可以通过v-for循环生成。月份切换功能通过计算属性动态更新日期数组。 <templat…