云开发(微信

您所在的位置:网站首页 点赞的云 云开发(微信

云开发(微信

2024-07-12 03:50| 来源: 网络整理| 查看: 265

云开发(微信-小程序)笔记(十四)---- 收藏,点赞(上)

1.存在的问题与解决方案

在前面我们介绍了收藏,点赞功能的实现,但还是存在一定的问题,没有实时的与数据库同步。为了这个问题,我们将结合云函数(可以修改所有用户创建的数据)来解决。

2.具体优化 2-1.在数据库中添加点赞,收藏字段

在这里插入图片描述

2-2.编写云函数 // 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 云函数入口函数 exports.main = async (event, context) => { if (event.action == 'shouchang'){ return await cloud.database().collection('Goods').doc(event.id) .update({ data: { shouchang: event.shouchang } }) .then(res =>{ console.log('收藏状态成功',res) return res }) .catch( res =>{ console.log('收藏状态失败',res) return res }) }else{ return await cloud.database().collection('Goods').doc(event.id) .update({ data: { dianzan: event.dianzan } }) .then(res =>{ console.log('点赞状态成功',res) return res }) .catch( res =>{ console.log('点赞状态失败',res) return res }) } }

一定要上传自己的修改,否者云函数是不会生效的。

2-3.修改tubiao.js文件 // pages/tubiao/tubiao.js let ID = '' let shouchang = false let dianzan = false Page({ data: { shouchangUrl: "../../imgs/chang-no.png ", dianzanUrl: "../../imgs/zan-no.png", }, onLoad(res){ console.log(res) ID = 'b69f67c06268c88b005446ac66f0ad09' wx.cloud.database().collection('Goods') .doc(ID) .get() .then(res => { console.log('详情页成功',res) shouchang=res.data.shouchang dianzan=res.data.dianzan this.setData({ detail: res.data, shouchangUrl:shouchang?"../../imgs/chang-yes.png":"../../imgs/chang-no.png", dianzanUrl:dianzan?"../../imgs/zan-yes.png":"../../imgs/zan-no.png" }) }) .catch(res =>{ console.log('请求数据失败',res) }) }, //收藏(三目运算符) clickMe1(){ this.setData({ shouchangUrl:shouchang?"../../imgs/chang-no.png":"../../imgs/chang-yes.png" }) shouchang = !shouchang //取反(收藏与未收藏之间的切换) //调用云函数 wx.cloud.callFunction({ name: "tubiao", //云函数名 data: { action:"shouchang", id: ID, shouchang: shouchang } }).then(res => { console.log('收藏成功') }).catch(res => { console.log('收藏失败') }) }, //收藏(三目运算符) clickMe2(){ this.setData({ dianzanUrl:dianzan?"../../imgs/zan-no.png":"../../imgs/zan-yes.png" }) dianzan = !dianzan //取反(点赞与未点赞之间的切换) //调用云函数 wx.cloud.callFunction({ name: "tubiao", data: { action:"dianzan", id: ID, dianzan: dianzan } }).then(res => { console.log('点赞成功') }).catch(res => { console.log('点赞失败') }) }, }) 2-4.修改tubiao.wxml文件(无修改)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3