小程序页面
<view class="box"> <block wx:for="{{ article }}" wx:key="key"> <view class="article"> <view class="author">{{ item.author_name }}</view> <view class="title" bindtap="getArticleInfo" data-article_id="{{ item.id }}">{{ item.title }}</view> <view class="content">{{ item.content }}</view> <view class="article-like"> <image wx:if="{{ item.like_status == 1 }}" src="/images/like/like.png" bindtap="articleLike" data-article_id="{{ item.id }}"></image> <image wx:else src="/images/like/nolike.png" bindtap="articleLike" data-article_id="{{ item.id }}"></image> </view> </view> </block> </view>
js
data: { article:[], page:1, limit:4, likes:false }, /** * 生命周期函数--监听页面加载 */ onl oad: function (options) { let page = this.data.page let limit = this.data.limit let token = wx.getStorageSync('token') wx.request({ url: 'http://www.1902a.com/article?page='+page+'&limit='+limit, header:{ token:token }, success:res=>{ // console.log(res.data.result) let article = res.data.result this.setData({ article }) } }) }, articleLike(e){ // console.log(e.currentTarget.dataset.article_id) var article_id = e.currentTarget.dataset.article_id let token = wx.getStorageSync('token') if(token==''){ wx.navigateTo({ url: '/pages/login/login', }) return } // console.log(token) wx.request({ url: 'http://www.1902a.com/like_article', header:{ token:token }, data:{ article_id:article_id }, method:'POST', success:res=>{ // console.log(res) //判断是否点赞成功 var arr = this.data.article; //1 没有返回值 这里面重新赋值只能用for不能each也不用foreach for (var i=0;i<arr.length;i++) { if(arr[i]['id'] == article_id){ if(res.data.errCode == 1){ arr[i]['like_status'] = 1; }else{ arr[i]['like_status'] = 0; } } } this.setData({ article:arr }) // console.log(arr) } }) },
PHP 后端
/** * 分页列表 * * @return void */ public function getNewsList() { $data = UserArticle::all(); // dump($data);die; //接收数据 $page = input('page'); $limit = input('limit'); // return checkJson($page);die; //偏移量 $mount = ($page-1)*$limit; $newsList = NewsInfo::limit($mount,$limit)->select(); foreach($newsList as $k=>&$v){ foreach($data as $key=>$val){ if($v['id']==$val['uid']){ $v['like_status'] = 1; } } } return checkJson($newsList); } /** * 点赞 * * @return void */ public function articleLike() { $article_id = input('article_id'); //取出用户id $uid = (new Token)->getCurrentKey('id'); // $data = UserArticle::where([ 'uid'=>$uid, 'article_id'=>$article_id ])->find(); if(!empty($data)){ //如果有数据就删除,取消点赞 $data->delete(); return checkJson([],'取消点赞成功',0); } UserArticle::create([ 'uid'=>$uid, 'article_id'=>$article_id ],true); return checkJson([],'点赞成功',1); }
进入详情页面时查看是否点赞
public function articleDetail() { $article_id = input('article_id'); $articleDetail = NewsInfo::find($article_id); //查询是否点赞 $data = UserArticle::all(); foreach($data as $key=>$val){ if($articleDetail['news_id']==$val['article_id']){ $articleDetail['like_status'] = 1; } } return checkJson($articleDetail); }