微信小程序结合laravel8实现点赞功能
wx.ml
<view bindtap="haveSave" data-id="{{headHouseDetails.id}}"> <view> <image class="save " src="{{isClick?'/images/shou(1)(1).png':'/images/shou1.png'}}" style="width: 100rpx;height: 100rpx;" ></image> </view> <view> <text class="saveText">{{isClick?'取消':'收藏'}}</text> </view> </view>
wx.js
/** * 页面的初始数据 */ data: { isClick: false, },
/** * 收藏 * @param {*} options */ haveSave(e) { // 获取文章id let id=e.currentTarget.dataset.id; // 获取token let token=wx.getStorageSync('token') wx.request({ url: `${config.baseUrl}collection`, //仅为示例,并非真实的接口地址 header: {token}, data: { id }, success: res => { if( res.data.code==200){ wx.showToast({ title: '收藏成功', }) this.setData({ isClick:true }) return }else if(res.data.code==204){ wx.showToast({ title: '取消收藏', }) this.setData({ isClick:false }) return }else{ wx.showToast({ title: '接口错误', }) } } }) },
laravel8 路由:
//点赞 Route::get('collection',[\App\Http\Controllers\HomePage\DataStorage\DataStoreageController::class,'collection'])->middleware(\App\Http\Middleware\CheckApiLogin::class);
控制器代码:
/** * 收藏楼盘信息 *users:闫兵 *Data:2022/4/22 *Time:18:36 */ public function collection(Request $request) { //接受要收藏的房源id 并验证 if (empty($request->get('id')) || !is_numeric($request->get('id'))) { return Msg(501, 'id错误', ''); } // 获取用户id: $userId = $request->get('user_id'); //将用户id和房源id添加到点赞表中 $where = [ 'user_id' => $request->get('user_id'), 'did' => $request->get('id'), ]; $model = Factory::collection(); $result = $model->where($where)->first(); if (empty($result)) { // 进行收藏 $addRes=$model->insertGetId($where); return Msg(200,'收藏成功',$addRes); }else{ //删除 $delRes = $model::where($where)->delete(); return Msg(204,'取消收藏',$delRes); }
效果图: