vue个人博客开发记录-实现文章点赞功能(三)

1.后端

1.1 增加文章中点赞对应的规则
const articleSchema = monoogse.Schema({
  categories:[{
    type:monoogse.SchemaTypes.ObjectId,
    ref:Category
  }],
  .....省略
  //添加点赞对应的规则,关联User(用户表)
  praise:[{
    type:monoogse.SchemaTypes.ObjectId,
    ref:'User'
  }]
1.2 增加对应的接口
  • type来判断是否点赞,当type=1时,表示用户点赞,当type=-1时,表示用户要取消点赞
  • $addToSet:向数组中添加元素,若数组本身含有该元素,则不添加,否则,添加,这样就避免了数组中的元素重复现象
  • $pull:删除数组中的指定数据
  //点赞接口
  router.post('/praise',async (req,res)=>{
    console.log(req.body)
    const {articleId,userId,type} = req.body
    if(type === 1){
      // 点赞
      await Article.update({_id:articleId},{$addToSet:{praise:userId}},{new:true})
      res.status(200).send('点赞成功')
    }else if(type === -1){
      // 取消点赞
      // 删除内嵌数组指定数据 使用操作符 $pull
      const model = await Article.update({_id:articleId},{$pull:{'praise':userId}})
      console.log(model)
      res.status(200).send('取消点赞')
    }
  })

2.文章详情页

2.1 在data中声明isClick来控制点赞的样式
	data(){
	      return {
	        model: {},
	        isClick:false
	      }
	    }
2.2 观察model的变化
  • model指的是文章详情数据,当model变化时调用showPraise方法,并且把最新的model当做参数传入,用includes方法来判断用户是否点赞过该篇文章。
	watch:{
      model(newValue){
        this.showPraise(newValue)
      }
    }
    methods:{
		showPraise(newModel){
	        const res = newModel.praise.includes(this.$store.state.currentUser._id)
	        if(this.$store.state.isLogin && res) {
	          this.isClick = true
	        }
	      }
	}
2.3 点赞或取消点赞
  • 点赞接口:postPraise(传入文章ID,用户ID,类型)
//点赞接口
export function postPraise(articleId,userId,type) {
  return request({
    url:'/praise',
    data:{articleId,userId,type},
    method:'post'
  })
}
  • 视图层
<div class="another ml-2">
      <div class="another-item" @click="praiseClick">
        <span class="iconfont icon-dianzan" :class="{active:isClick}"/>
        <p :class="{active:isClick}">点赞</p>
      </div>
     <div class="another-item">
       <span class="iconfont icon-huifu comment"/>
       <p>评论</p>
     </div>
    </div>
  • 逻辑层
async praiseClick(){
        if (this.$store.state.isLogin){
          if(this.isClick){
            console.log('取消点赞')
            await postPraise(this.id,this.$store.state.currentUser._id,-1)
            this.isClick = false
          } else {
            console.log('点赞')
            await postPraise(this.id,this.$store.state.currentUser._id,1)
            this.isClick = true
          }
        } else{
          this.$Message.warning('请先登录')
        }
      }
2.4 实现点赞或取消点赞的效果如下
  • 用户点赞成功如下:
    在这里插入图片描述

  • 用户取消点赞如下:
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43950643/article/details/107494950
今日推荐