云开发学习7--基础综合案例(无页面优化的简单商城小程序,以实现功能为主)

2021/10/26 17:09:45

本文主要是介绍云开发学习7--基础综合案例(无页面优化的简单商城小程序,以实现功能为主),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一,基础知识部分

1.更改小程序上方标语

  • 修改json文件(对应界面,若在app.json中则所有页面都应用)
 "navigationBarTitleText": "小香猪商城",

2.两种弹窗方法应用(showToast、showModal)

  • wx.showToast
    函数文档
 wx.showToast({
        icon: "none",//不带就是一个对号
        title: '商品名为空,请重新输入',
      })

在这里插入图片描述

  • wx.showModal (在本案例中用于,删除数据前的友好提示)
    函数文档
//删除前的友好提示,危险操作!!
    wx.showModal({
      title: "是否确定删除",
      content: "删除操作很危险,无法撤回,请三思!",
      success(res) {
        if (res.confirm) {
          console.log("用户点击了确定")
          //删除操作
          //*************本地方法删除数据******************* */
          wx.cloud.database().collection("goods")
            .doc(id)
            .remove()
            .then(res => {
              console.log("本地方法删除成功", res)
            })
            .catch(err => {
              console.log("本地方法删除失败", err)
            })
          //*************云函数方法删除数据******************* */
          wx.cloud.callFunction({
            name: "removedata",
            data: {
              id: id
            }
          }).then(res => {//成功
            console.log("云函数删除数据成功", res)
            //返回首页
            wx.navigateTo({
              url: '/pages/zhujiemian/zhujiemian',
            })
              .catch(err => {//失败
                console.log("云函数删除数据失败", err)
              })
          })
        } else if (res.cancle) {
          console.log("用户点击了取消")
        }
      }
    })

在这里插入图片描述

3.加载图片的使用

  • 加载图标开启
    wx.showLoading({ //设置加载中图标
      title: '加载中。。。。。',
    })
  • 加载图标结束

4.更改数据库数据时权限问题解决

在这里插入图片描述

5.跳转详情页携带数据方法

  • 主界面传输数据
  //跳转到详情页
  goDetail(e) {
    // console.log("点击了详情页", e)//dataset
    // console.log("点击了详情页", e.currentTarget.dataset.name)//dataset
    // console.log("点击了详情页", e.currentTarget.dataset.id)//dataset
    wx.navigateTo({
      url: '/pages/shangpinye/shangpinye?id=' + e.currentTarget.dataset.id,//跳转到详情页并携带id(重点)
    })
  },
  • 详情页接受数据
  onl oad(options) {
    //查询单条数据
    var id = "" //此变量需改为全局变量,放在这里是保持代码展示的完整性
    id = options.id //取出携带的id数据,从主界面获取商品id
    this.getDetail()
  },

6.上传本地参数到云函数(以云函数删除为例)

  • 调用云函数的删除操作,将数据id上传至云函数
wx.cloud.callFunction({
            name: "removedata",
            data: {
              id: id
            }
          }).then(res => {//成功
            console.log("云函数删除数据成功", res)
            //返回首页
            wx.navigateTo({
              url: '/pages/zhujiemian/zhujiemian',
            })
              .catch(err => {//失败
                console.log("云函数删除数据失败", err)
              })
  • 云函数中通过对event的属性进行访问,来获取传输过来的数据
exports.main = async (event, context) => {
  return cloud.database().collection("goods")
  .doc(event.id)
  .remove()
}

二,整体代码展示

1.数据库数据格式

在这里插入图片描述

2.云函数结构以及代码

  • 云函数结构
    在这里插入图片描述
  • adddata函数
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.database().collection("goods")
    .add({
      data: {
        name: event.name,
        price: parseFloat(event.price)
      }
    })
}
  • fenye函数
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  return await cloud.database().collection("goods")
    .skip(event.len)//分页
    .limit(event.pageNum)//每页加载多少
    .get()
}
  • removedata函数
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.database().collection("goods")
  .doc(event.id)
  .remove()
}
  • updatedata函数
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.database().collection("goods")
    .doc(event.id)
    .update({
      data: {
        price: parseFloat(event.price) //当数据为数值型时,为保险起见需要进行数据类型的转化
      }
    })
}
  • getdata函数
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.database().collection("goods").get()

}

3.本地代码

  • 效果展示
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

1.主界面代码

  • js文件
// 全局变量
let name = "" //用于商品名暂存
let price = "" //用于价格暂存
let data = ""  //用于数据暂存
var i = 0 //用于循环计数
let len = 0//用于统计当前已经展示的数据数量,用于分页展示数据

Page({
  data: {
    list: [],
    block_name: "",
    block_price: "",
    iffenye: true  //暂时设定所有按键都存在
  },
  onl oad() {
    wx.startPullDownRefresh() //启动刷新动画
    this.getList()
  },//onload结束
  onShow() {//切回主界面时,实时更新数据
    this.getList()
  },

  //刷新页面
  getList() {
    wx.cloud.database().collection("goods")//在collection中设置数据库集合的名称
      .get()
      .then(res => {
        // console.log("商品列表请求成功", res)
        wx.stopPullDownRefresh() //结束刷新动画
        this.setData({
          list: res.data //若果需要前端的数据绑定通过setData方式进行设置
        })
      })
      .catch(err => {
        console.log("商品列表请求失败", err)
      })
  },

  //跳转到详情页
  goDetail(e) {
    // console.log("点击了详情页", e)//dataset
    // console.log("点击了详情页", e.currentTarget.dataset.name)//dataset
    // console.log("点击了详情页", e.currentTarget.dataset.id)//dataset
    wx.navigateTo({
      url: '/pages/shangpinye/shangpinye?id=' + e.currentTarget.dataset.id,//跳转到详情页并携带id
    })
  },

  //获取用户输入的商品名
  getName(e) {
    name = e.detail.value
  },
  //获取用户输入的商品价格
  getPrice(e) {
    price = e.detail.value
  },

  //添加商品信息到数据库
  addGood(e) {
    if (name == "") {
      console.log("商品名为空,请重新输入")
      wx.showToast({
        icon: "none",//不带就是一个对号
        title: '商品名为空,请重新输入',
      })
    } else if (price == "") {
      console.log("商品价格为空,请重新输入")
      wx.showToast({
        icon: "none",//不带就是一个对号
        title: '商品价格为空,请重新输入',
      })
    } else {//添加操作
      //*****************本地方法添加数据********************/
      // wx.cloud.database().collection("goods") //选择数据集合
      //   .add({
      //     data: {//根据数据集合的结构给出需要添加的数据
      //       name: name,
      //       price: parseFloat(price)
      //     }
      //   })
      //   .then(res => {
      //     console.log("添加成功")
      //     this.getList() //更新页面显示数据
      //     this.setData({ //清空用户输入框
      //       block_name: "",
      //       block_price: ""=
      //     })
      //   })
      //   .catch(err => {
      //     console.log("添加失败")
      //   })
      //*****************云函数方法添加数据********************/
      wx.cloud.callFunction({
        name: "adddata",
        data: {
          name: name,
          price: price,
        }
      }).then(res => {
        console.log("添加成功")
        this.getList()
        this.setData({
          block_name: "",
          block_price: ""
        })
      })
        .catch(err => {
          console.log("添加失败")
        })
    }
  },

  //***************************************数据库高级用法**************************** */
  //商品价格升序排序
  shengxu() {
    wx.cloud.database().collection("goods")
      .orderBy("price", "asc")
      .get()
      .then(res => {
        this.setData({
          list: res.data
        })
      })
      .catch(err => {
        console.log("升序排列失败", err)
      })
  },
  //商品价格降序排序
  jiangxu() {
    wx.cloud.database().collection("goods")
      .orderBy("price", "desc")//给出根据数据的哪个属性来进行数据排序,并给出排序方式:asc升序,desc降序
      .get()
      .then(res => {
        this.setData({
          list: res.data  //将排序后的数据通过数据绑定显示到前端界面上
        })
      })
      .catch(err => {
        console.log("排列失败", err)
      })
  },

  //limit返回指定条数数据,演示为三条,最上面三条
  limit_show() {
    wx.cloud.database().collection("goods")
      .limit(3) //返回最上面三条数据
      .get()
      .then(res => {
        this.setData({
          list: res.data
        })
      })
      .catch(err => {
        console.log("数据返回失败", err)
      })
  },

  //跳过指定条数据,演示为2两条
  skip_show() {
    wx.cloud.database().collection("goods")
      .skip(2)  //跳过最开始得1两条数据
      .get()
      .then(res => {
        this.setData({
          list: res.data //将筛选后的数据返回到前端界面
        })
      })
      .catch(err => {
        console.log("数据跳过失败", err)
      })
  },

  //大于30+等于
  dayu_show() {
    let db = wx.cloud.database()//这段属于重复代码,便于展示才放在此处,应放在onload中
    db.collection("goods")
      .where({
        price: db.command.gt(30),//大于
        // price: db.command.gte(30),//大于等于
      })
      .get()
      .then(res => {
        console.log("成功")
        this.setData({
          list: res.data
        })
      })
      .catch(err => {
        console.log("失败")
      })


  },

  //小于100+等于
  xiaoyu_show() {
    let db = wx.cloud.database()//这段属于重复代码,便于展示才放在此处,应放在onload中
    db.collection("goods")
      .where({
        price: db.command.lt(30),//小于
        // price: db.command.lte(30),//小于等于
      })
      .get()
      .then(res => {
        console.log("成功")
        this.setData({
          list: res.data
        })
      })
      .catch(err => {
        console.log("失败")
      })
  },

  //大于30,小于100
  daxiaoyu_show() {
    let db = wx.cloud.database()//这段属于重复代码,便于展示才放在此处,应放在onload中
    const _ = db.command
    db.collection("goods")
      .where(_.and([
        {
          price: db.command.gt(30),//大于
          // price: db.command.gte(30),//大于等于
        },
        {
          price: db.command.lt(100),//小于
          // price: db.command.lte(100),//小于等于
        },
      ]))
      .get()
      .then(res => {
        console.log("成功")
        this.setData({
          list: res.data
        })
      })
      .catch(err => {
        console.log("失败")
      })
  },

  //统一修改商品价格
  tongyixiugai() {
    wx.cloud.callFunction({
      name: "getdata",
    }).then(res => {
      console.log("查找数据成功", res)
      //修改数据
      data = res.result.data
      for (; i < data.length; i++) {
        wx.cloud.callFunction({
          name: "updatedata",
          data: {
            id: data[i]._id,
            price: 100,
          }
        }).then(res => {
          console.log("修改数据成功", res)
          this.getList()
        })
          .catch(err => {
            console.log("修改数据失败", err)
          })
      }

    })
      .catch(err => {
        console.log("查找数据失败", err)
      })
  },

  /分页操作
  fenye_getList() {
    wx.showLoading({ //设置加载中图标
      title: '加载中。。。。。',
    })
    console.log("当前list内容", this.data.list)
    console.log("当前list的长度", this.data.list.length)
    len = this.data.list.length

    //调用云函数
    wx.cloud.callFunction({
      name: "fenye",
      data: {
        pageNum: 1,//每页加载一个
        len: len,//分页用的
      }
    }).then(res => {
      wx.hideLoading() //加载完成后隐藏加载图标
      console.log("云函数获取数据成功", res)
      if (res.result.data.length <= 0) {  //没有更多数据的友好提示
        wx.showToast({
          icon: "none",
          title: '没有更多数据了',
        })
      }
      this.setData({
        list: this.data.list.concat(res.result.data)
      })

    }).catch(err => {
      wx.hideLoading() //加载完成后隐藏加载图标
      console.log("调用失败", err)
    })

  },
  //分页操作演示
  fenye() {
    this.setData({
      iffenye: false,
      list: []
    })
    this.fenye_getList()

  },

  //退出分页展示
  tuichufenye() {
    this.setData({
      iffenye: true
    })
    this.getList()

  },

  //分页的下一页展示操作,需结合云函数fenye
  fenye_xiayiye() {
    this.fenye_getList()
  }
  
})
  • json文件
{
  "usingComponents": {},
  "navigationBarTitleText": "小香猪商城",
  "enablePullDownRefresh": true,  
  "backgroundColor": "#d3d3d3"
}
  • wxml文件
<!-- 实现功能 -->
<!-- 
1.能查看商品列表
2.能动态添加商品
3.能进入商品详情页
4.能删除某个商品
5.能修改某个商品的价格 -->

<input bindinput="getName" placeholder="请输入商品名" value="{{block_name}}"></input>
<input bindinput="getPrice" placeholder="请输入商品价格" value="{{block_price}}"></input>
<button bindtap="addGood" type="primary">添加商品</button>

<view>*******所有商品价格列表*******</view>
<view  wx:for="{{list}}">
  <!-- dataset 点击跳转时携带数据 -->
  <view bindtap="goDetail" data-name="{{item.name}}" data-id="{{item._id}}">商品名:{{item.name}},价格:{{item.price}}</view>
</view>
<button wx:if="{{iffenye}}" bindtap="shengxu" type="primary">点击升序排列</button>
<button wx:if="{{iffenye}}" bindtap="jiangxu" type="primary">点击降序排列</button>
<button wx:if="{{iffenye}}" bindtap="limit_show" type="primary">返回指定条数据,演示三条</button>
<button wx:if="{{iffenye}}" bindtap="skip_show" type="primary">跳过指定条数据,演示两条</button>
<button wx:if="{{iffenye}}" bindtap="dayu_show" type="primary">大于30</button>
<button wx:if="{{iffenye}}" bindtap="xiaoyu_show" type="primary" >小于100</button>
<button wx:if="{{iffenye}}" bindtap="daxiaoyu_show" type="primary">大于30,小于100</button>
<button wx:if="{{iffenye}}" bindtap="tongyixiugai" type="primary">统一修改价格为100(参考)</button>


<!-- 分页操作 -->

<button  bindtap="fenye" type="primary">分页展示</button>

<button wx:if="{{!iffenye}}" bindtap="fenye_xiayiye" type="primary">下一页</button>

<button wx:if="{{!iffenye}}" bindtap="tuichufenye" type="primary">退出分页展示</button>

  • wxss文件
input{
  border: 3rpx solid black;
  margin: 20rpx 0;
}
button{
  margin: 20rpx 0;
}

2.详情页代码

  • js文件
//全局变量
let price = ""
var id = ""

Page({
  data: {
    good: {},
    block_price: ""
  },
  onl oad(options) {
    //查询单条数据
    id = options.id //取出携带的id数据,从主界面获取商品id
    this.getDetail()
  },


  //获取用户输入的新价格
  getPrice(e) {
    price = e.detail.value
  },

  //获取商品数据
  getDetail() {
    wx.cloud.database().collection("goods")
      .doc(id)//将携带的id数据放到指定位置进行查询
      .get()
      .then(res => {
        // console.log("商品详情页请求成功", res)
        this.setData({
          good: res.data,
        })
        
      })
      .catch(err => {
        console.log("商品详情页请求失败", err)
      })
  },

  //更新价格
  update() {
    if (price == "") {
      wx.showToast({
        icon: "none",
        title: '修改价格为空',
      })
    } else {
      //*************本地方法更新数据******************* */
      // wx.cloud.database().collection("goods")
      //   .doc(id) //需给出数据对应的id
      //   .update({
      //     data: { //给出对应数据需要修改的属性以及修改值
      //       price: price
      //     }
      //   })
      //   .then(res => {//成功
      //     // console.log("本地方法修改数据成功")
      //     this.getDetail() //更新页面数据
      //   })
      //   .catch(err => {//失败
      //     // console.log("本地方法修改数据失败")
      //   })
      //*************云函数方法更新数据******************* */
      wx.cloud.callFunction({
        name: "updatedata",
        data: {
          id: id,
          price: parseFloat(price),//逗号一定不能省!!!!
        }
      })
        .then(res => {//成功
          console.log("云函数修改数据成功", res)
          this.getDetail()
          this.setData({
            block_price: ""
          })
        })
        .catch(err => {//失败
          console.log("云函数修改数据失败", err)
        })
    }
  },

  //删除当前商品
  remove(e) {
    console.log("点击了删除", id)

    //删除前的友好提示,危险操作!!
    wx.showModal({
      title: "是否确定删除",
      content: "删除操作很危险,无法撤回,请三思!",
      success(res) {
        if (res.confirm) {
          console.log("用户点击了确定")
          //删除操作
          //*************本地方法删除数据******************* */
          wx.cloud.database().collection("goods")
            .doc(id)
            .remove()
            .then(res => {
              console.log("本地方法删除成功", res)
            })
            .catch(err => {
              console.log("本地方法删除失败", err)
            })
          //*************云函数方法删除数据******************* */
          wx.cloud.callFunction({
            name: "removedata",
            data: {
              id: id
            }
          }).then(res => {//成功
            console.log("云函数删除数据成功", res)
            //返回首页
            wx.navigateTo({
              url: '/pages/zhujiemian/zhujiemian',
            })
              .catch(err => {//失败
                console.log("云函数删除数据失败", err)
              })
          })
        } else if (res.cancle) {
          console.log("用户点击了取消")
        }
      }
    })
  },


})
  • json文件
{
  "usingComponents": {},
  "navigationBarTitleText": "商品详情页"
}
  • wxml文件
<view>商品名:{{good.name}},价格名:{{good.price}}</view>
<!-- 显示货物详情图片,数据库中数据需要设置图片的网络地址,地址需要在云存储中获取 -->
<image src="{{good.img}}"></image>
<view>更新价格</view>
<input bindinput="getPrice" placeholder="请输入修改价格" value="{{block_price}}"></input>
<button type="primary" bindtap="update">更新商品价格</button>
<button type="primary" bindtap="remove">删除当前商品</button>
  • wxss文件
/* pages/shangpinye/shangpinye.wxss */
input{
  border: 3rpx solid black;
  margin: 20rpx 0;
}
button{
  margin: 20rpx 0;
}


这篇关于云开发学习7--基础综合案例(无页面优化的简单商城小程序,以实现功能为主)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程