5.評論和關(guān)注功能

1.數(shù)據(jù)表
  • 新增t_follow表


    follow.png
2.entity包
  • Follow實體類
@Data
public class Follow {
    private Integer id;
    private Integer fromUId;
    private Integer toUId;
}
  • FollowVO 視圖對象類
@Data
public class FollowVO {
    private Integer toUId;
    private String nickname;
    private String avatar;
}
3.Mapper
  • FollowMapper
public interface FollowMapper {

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "fromUId", column = "from_uid"),
            @Result(property = "toUId", column = "to_uid")
    })
    @Select("SELECT * FROM t_follow WHERE from_uid = #{fromUId} AND to_uid = #{toUId} ")
    Follow getFollow(@Param("fromUId") int fromUId, @Param("toUId") int toUId);

    @Results({
            @Result(property = "toUId", column = "to_uid"),
            @Result(property = "nickname", column = "nickname"),
            @Result(property = "avatar", column = "avatar")
    })
    @Select("SELECT a.to_uid,b.nickname,b.avatar FROM t_follow a LEFT JOIN t_user b ON a.to_uid = b.id WHERE a.from_uid = #{fromUId}  ")
    List<FollowVO> getFollowsByUId(int fromUId);

    @Insert("INSERT INTO t_follow (from_uid,to_uid) VALUES (#{fromUId},#{toUId}) ")
    void insertFollow(Follow follow);

    @Delete("DELETE  FROM t_follow WHERE from_uid = #{fromUId} AND to_uid = #{toUId} ")
    void deleteFollow(@Param("fromUId") int fromUId, @Param("toUId") int toUId);
}
  • CommentMapper增加方法
@Insert("INSERT INTO t_comment(u_id,a_id,content,comment_time) VALUES(#{uId}, #{aId}, #{content},#{commentTime}) ")
void insert(Comment comment);
4.service
  • FollowService
public interface FollowService {
    Follow getFollow(int fromUId, int toUId);

    List<FollowVO> getFollowsByUId(int fromUId);

    void insertFollow(Follow follow);

    void deleteFollow(int fromUId, int toUId);
}
  • CommentService
public interface CommentService {
    List<CommentVO> selectCommentsByAId(int aId);
    void addComment(Comment comment);
}
  • service實現(xiàn)類及單元測試省略
5.controller
  • FollowController
@RestController
@RequestMapping(value = "/api/follow")
public class FollowController {
    @Resource
    private FollowService followService;


    @PostMapping("/add")
    public ResponseResult followUser(@RequestParam("fromUId") int fromUId, @RequestParam("toUId") int toUId) {
        Follow follow = new Follow();
        follow.setFromUId(fromUId);
        follow.setToUId(toUId);
        followService.insertFollow(follow);
        return ResponseResult.success();
    }

    @PostMapping("/cancel")
    public ResponseResult cancelFollow(@RequestParam("fromUId") int fromUId, @RequestParam("toUId") int toUId) {
        followService.deleteFollow(fromUId, toUId);
        return ResponseResult.success();
    }
}
  • CommentController
@RestController
@RequestMapping(value = "/api/comment")
public class CommentController {
    @Resource
    private CommentService commentService;

    @PostMapping("/add")
    public ResponseResult addComment(@RequestParam("aId") int aId, @RequestParam("uId") int uId, @RequestParam("content") String content) {
        Comment comment = new Comment();
        comment.setAId(aId);
        comment.setUId(uId);
        comment.setContent(content);
        comment.setCommentTime(new Date());
        commentService.addComment(comment);
        return ResponseResult.success();
    }
}
  • 修改一下ArticleController接口中的根據(jù)id獲取文章的方法童漩,增加一個參數(shù):登錄用戶的id,來判斷登錄用戶是否已經(jīng)關(guān)注了文章作者
@GetMapping(value = "/{aId}")
public ResponseResult getArticleById(@PathVariable("aId") int aId,@RequestParam("userId") int userId) {
    ArticleVO article = articleService.getArticleById(aId);
    int toUId = article.getUId();
    Map<String, Object> map = new HashMap<>();
    Follow follow = followService.getFollow(userId, toUId);
    if (follow != null) {
        map.put("followed", MsgConst.FOLLOWED);
    } else {
        map.put("followed", MsgConst.NO_FOLLOWED);
    }
    List<CommentVO> comments = commentService.selectCommentsByAId(aId);
    map.put("article", article);
    map.put("comments", comments);
    return ResponseResult.success(map);
}
6.swagger測試
7.前端
  • 文章詳情頁
<template>
    <view class="container">
        <text class="article-title">{{ article.title }}</text>
        <view class="article-info">
            <image :src="article.avatar" class="avatar small"></image>
            <text style="margin-left: 10px;">{{ article.nickname }}</text>
            <text class="info-text">{{ handleTime(article.createTime)}}</text>
            <!-- 登錄用戶和文章作者不是同一個人,就顯示關(guān)注或取消關(guān)注按鈕 -->
            <button v-if="userId != article.uId && !followed" class="btn follow-btn" @tap="follow">+ 關(guān)注</button>
            <button v-if="userId != article.uId && followed" class="btn follow-btn cancel" @tap="cancelFollow">取消</button>
        </view>

        <view class="grace-text" style="margin-top: 10px;">
            <rich-text :nodes="article.content" bindtap="tap"></rich-text>
        </view>
        <button v-if="!liked" class="like-btn" @tap="like">收藏 </button>
        <button  v-if="liked" class="cancel-like" @tap="cancelLike">取消</button>
        <text class="info-text">評論 {{ comments.length }}</text>
        <view class="comment-item" v-for="(comment, index) in comments" :key="index">
            <view class="left">
                <image :src="comment.avatar" class="avatar small"></image>
            </view>
            <view class="right">
                <view class="right-content">
                    <text>{{ comment.nickname }}</text>
                    <text>{{ comment.content }}</text>
                </view>
                <view class="right-time">
                    <text style="margin-right: 10px;">{{ comments.length - index }}樓·{{comment.commentTime}}</text>
                    <!-- <text>{{  handleTime(comment.commentTime)}}</text> -->
                </view>
            </view>
        </view>
        
        <input class="uni-input comment-box" type="text" placeholder="寫下你的評論" v-model="content" required="required" />
        <button class="green-btn" @tap="send">提交</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                article: {
                    aId: 0,
                    uId: 0,
                    title: '',
                    content: '',
                    avatar: '',
                    nickname: '',
                    createTime: ''
                },
                comments: [],
                content: '',
                userId: uni.getStorageSync('login_key').userId,
                followed: false,
                liked:false
            };
        },
        onLoad: function(option) {
            //option為object類型,會序列化上個頁面?zhèn)鬟f的參數(shù)
            this.article.aId = option.aId;
        },
        onShow: function() {
            this.getArticle();
        },
        onPullDownRefresh: function() {
            this.getArticle();
        },
        methods: {
            getArticle: function() {
                var _this = this;
                uni.request({
                    url: this.apiServer + '/article/' + this.article.aId,
                    method: 'GET',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        userId: this.userId
                    },
                    success: res => {
                        // console.log(res.data.data.article);
                        _this.article.aId = res.data.data.article.id;
                        _this.article.uId = res.data.data.article.uid;
                        _this.article.title = res.data.data.article.title;
                        _this.article.content = res.data.data.article.content;
                        _this.article.nickname = res.data.data.article.nickname;
                        _this.article.avatar = res.data.data.article.avatar;
                        _this.article.createTime = res.data.data.article.createTime;
                        _this.comments = res.data.data.comments;
                        if (res.data.data.followed === '已關(guān)注') {
                            _this.followed = true;
                        }
                    },
                    complete: function() {
                        uni.stopPullDownRefresh();
                    }
                });
            },
            handleTime: function(date) {
                var d = new Date(date);
                var year = d.getFullYear();
                var month = d.getMonth() + 1;
                var day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate();
                var hour = d.getHours() < 10 ? '0' + d.getHours() : '' + d.getHours();
                var minutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : '' + d.getMinutes();
                var seconds = d.getSeconds() < 10 ? '0' + d.getSeconds() : '' + d.getSeconds();
                return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
            },
            send: function() {
                console.log('評論人編號:' + this.userId + ',文章編號:' + this.article.aId + ',評論內(nèi)容:' + this.content);
                uni.request({
                    url: this.apiServer + '/comment/add',
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        aId: this.article.aId,
                        uId: this.userId,
                        content: this.content
                    },
                    success: res => {
                        if (res.data.code === 0) {
                            uni.showToast({
                                title: '評論成功'
                            });
                            this.getArticle();
                            this.content = '';
                        }
                    }
                });
            },
            follow: function() {
                uni.request({
                    url: this.apiServer + '/follow/add',
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        fromUId: this.userId,
                        toUId: this.article.uId
                    },
                    success: res => {
                        if (res.data.code === 0) {
                            uni.showToast({
                                title: '關(guān)注成功'
                            });
                            this.followed = true;
                        }
                    }
                });
            },
            like: function() {
                uni.request({
                    url: this.apiServer + '/like/add',
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        uId: this.userId,
                        aId: this.article.aId
                    },
                    success: res => {
                        if (res.data.code === 0) {
                            uni.showToast({
                                title: '收藏成功'
                            });
                            this.liked = true;
                        }
                    }
                });
            },
            cancelFollow: function() {
                uni.request({
                    url: this.apiServer + '/follow/cancel',
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        fromUId: this.userId,
                        toUId: this.article.uId
                    },
                    success: res => {
                        if (res.data.code === 0) {
                            uni.showToast({
                                title: '已取消關(guān)注'
                            });
                            this.followed = false;
                        }
                    }
                });
            },
            cancelLike: function() {
                uni.request({
                    url: this.apiServer + '/like/cancel',
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        uId: this.userId,
                        aId: this.article.aId
                    },
                    success: res => {
                        if (res.data.code === 0) {
                            uni.showToast({
                                title: '已取消收藏'
                            });
                            this.liked = false;
                        }
                    }
                });
            }
        }
    };
</script>

<style>
    
    .link {
        cursor: pointer;
    }
    
    .article-title {
        font-weight: bold;
        padding: 10px;
        font-size: 22px;
    }

    .article-info {
        display: flex;
        margin-top: 20px;
        align-items: center;
    }

    .grace-text {
        margin-top: 10px;
    }

    .avatar {
        width: 60px;
        height: 60px;
        margin-left: 5px;
    }

    .info-text {
        margin-left: 10px;
        font-size: 18px;
        margin-top: 10px;
        display: flex;
        flex-direction: column;
    }

    .btn {
        margin-right: 10px;
        width: 90px;
        height: 40px;
        background: #00C777;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #EEEEEE;
    }

    .content {
        width: 90%;
        margin: auto;
    }

    .comment-item {
        display: flex;
        margin-top: 5px;
    }

    .right {
        display: flex;
        flex-direction: column;
        margin-left: 10px;
    }

    .right-content {
        display: flex;
        flex-direction: column;
    }

    .right-time {
        margin-top: 5px;
        color: #C1C1C1;
        font-size: 15px;
    }

    .uni-input {
        margin-top: 10px;
        font-size: 18px;
    }

    .green-btn {
        margin-top: 10px;
        width: 60%;
        cursor: pointer;
        border-radius: 10px;
        background: #00EE76;
        color: white;
    }

    .cancel {
        background-color:#AAAAAA;
    }
    .like-btn{
        width: 90px;
        height: 40px;
        background: white;
        display: flex;
        justify-content: center;
        align-items: center;
        color:#FF7900;
        border: 1px solid #FF7900;
        border-radius: 10px;
        margin-top: 10px;
    }
    .cancel-like{
        width: 90px;
        height: 40px;
        background-color: #aaa;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 10px;
        margin-top: 10px;
    }
    
</style>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末敢辩,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌麦射,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件灯谣,死亡現(xiàn)場離奇詭異法褥,居然都是意外死亡,警方通過查閱死者的電腦和手機酬屉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門半等,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人呐萨,你說我怎么就攤上這事杀饵。” “怎么了谬擦?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵切距,是天一觀的道長。 經(jīng)常有香客問我惨远,道長谜悟,這世上最難降的妖魔是什么话肖? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮葡幸,結(jié)果婚禮上最筒,老公的妹妹穿的比我還像新娘。我一直安慰自己蔚叨,他們只是感情好床蜘,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蔑水,像睡著了一般邢锯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上搀别,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天丹擎,我揣著相機與錄音,去河邊找鬼歇父。 笑死鸥鹉,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的庶骄。 我是一名探鬼主播毁渗,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼单刁!你這毒婦竟也來了灸异?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤羔飞,失蹤者是張志新(化名)和其女友劉穎肺樟,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體逻淌,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡么伯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了卡儒。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片田柔。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖骨望,靈堂內(nèi)的尸體忽然破棺而出硬爆,到底是詐尸還是另有隱情,我是刑警寧澤擎鸠,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布缀磕,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏袜蚕。R本人自食惡果不足惜糟把,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望牲剃。 院中可真熱鬧遣疯,春花似錦、人聲如沸颠黎。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽狭归。三九已至,卻和暖如春文判,著一層夾襖步出監(jiān)牢的瞬間过椎,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工戏仓, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留疚宇,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓赏殃,卻偏偏與公主長得像敷待,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子仁热,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容