Skip to content

点赞功能

需求分析

  • 后端提供点赞和取消点赞功能
  • 当用户点击未点赞按钮,执行点赞逻辑,向后端发起点赞请求,取消点赞则反之
  • 在文章显示完成之后,底部评论会根据当前登录用户显示是否点赞图标

接口设计

见接口文档

前端逻辑实现

给点赞的 a 标签添加自定义属性,以记录当前点赞的文章id和评论id,供点赞/取消点赞请求使用

html
{#给评论点赞#}
<a href="javascript:;"
   class="comment_up fr"
   data-commentid="{{ comment.id }}"
   data-newsid="{{ comment.news_id }}">赞</a>
<a href="javascript:;" class="comment_reply fr">回复</a>

实现点赞逻辑

JavaScript
// 实现点赞逻辑
$('.comment_up').click(function() {
    let action = 'add';

    if ($(this).hasClass('has_comment_up')) {
        // 如果当前该评论已经是点赞状态,再次点击会进行到此代码块内,代表要取消点赞
        action = 'remove';
    }

    const comment_id = $(this).parents('.comment-details').siblings('.reply_form').attr('data-commentid');
    const params = {
        'comment_id': comment_id,
        'action': action,
        'article_id': article_id,
    };

    $.ajax({
        url: '/article/comment_like',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(params),
        success: function(resp) {
            if (resp.code === 0) {
                window.location.reload();
                // 动态修改数据更新
            } else if (resp.code === 4101) {
                window.location.href = '/login';
            } else {
                alert(resp.message);
            }
        },
    });
});

后端代码实现

  • application/views/article.py 中添加点赞/取消点赞视图函数
python
@article_bp.route('/article/comment_like', methods=["POST"])
@login_required  # 过滤必须进行登录
def comment_like():
    """评论点赞"""
    # g.user current_user

    # 获取参数
    news_id = request.json.get("news_id")
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    # 查询评论数据
    try:
        comment = CommentModel.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return {'code': 4010, 'success': False, 'message': '点赞的评论不存在'}

    if not comment:
        return {'code': 4010, 'success': False, 'message': '点赞的评论不存在'}

    if action == "add":
        comment_like = CommentLikeModel.query.filter_by(comment_id=comment_id, user_id=current_user.id).first()
        if not comment_like:
            # 记录点赞关系
            comment_like = CommentLikeModel()
            comment_like.user_id = current_user.id
            comment_like.comment_id = int(comment_id)
            db.session.add(comment_like)
            # 增加点赞条数
            comment.like_count += 1
    else:
        # 删除点赞数据
        comment_like = CommentLikeModel.query.filter_by(comment_id=comment_id, user_id=current_user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            # 减小点赞条数
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return {"code": 4012, "mesage": "数据提交失败", "success": False}
    return {"code": 0, "mesage": "数据保存成功", "success": True}

点赞计数功能

  • 实现评论如果有点赞,就显示点赞的条数,并使用自定义属性记录当前条数
html
{#给评论点赞#}
<div class="comment-details">
    <div class="comment_time ">{{ comment.create_at }}</div>
    <div>
        <a href="javascript:;" class="comment_reply">回复</a>
        <a href="javascript:;"
           class="comment_up
                  {% for comm in current_user.commit_likes %}
                  {% if comm.comment_id == comment.id %}
                  has_comment_up
                  {% endif %}
                  {% endfor %}">
            {% if comment.like_count %}
            {{ comment.like_count }}
            {% else %}

            {% endif %}
        </a>
    </div>
</div>