小程序云开发

该博客详细介绍了如何在微信小程序中使用云开发进行数据的添加、查询、更新和删除操作,包括商品信息的录入、云函数进行加法运算、商品价格排序、分页加载和文件上传下载等。此外,还涉及到云函数更新商品价格和删除商品的逻辑,以及使用云存储上传图片和视频。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 项目配置云函数
    在这里插入图片描述

  2. 云开发环境配置
    在这里插入图片描述

  3. 添加数据

<button bindtap="add">点击添加数据</button>
<button bindtap="update">修改数据</button>
<button bindtap="remove">删除单条数据</button>
<input bindinput="getname" placeholder="请输入商品名称"></input>
<input bindinput="getprice" placeholder="请输入商品价格"></input>
<button bindtap="addgood">添加商品</button>
<view wx:for="{{list}}" wx:key="id">
 <view bindtap="goDatail" data-id="{{item._id}}">商品名:{{item.name}},价格:{{item.price}}</view>
</view>
<button bindtap="goodSort">按商品价格排序</button>


add(){
  wx.cloud.database().collection('goods')
  .add({
    data:{
      name:'车厘子',
      price:200
    }
  })
  .then(res =>{
   console.log('添加成功',res)
  })
  .catch(err =>{
    console.log('添加失败',err)
  })
 }
//添加商品到数据库
   addgood(){
     if(goodname ==''){
        wx.showToast({
          title: '商品名不能为空',
          icon:'none'
        })
     }else if(price==0 || price==''){
      wx.showToast({
        title: '商品价格不能为空',
        icon:'none'
      })
     }else{
      wx.cloud.database().collection('goods')
      .add({
        data:{
          name:goodname,
          price:parseInt(price)  //把字符串转换成数字
        }
      })
      .then(res =>{
         this.getList() 
      } )
      .catch(err =>{
        console.log('添加商品失败',err)
      })
     }
    }
  1. 云函数运算
    在这里插入图片描述
//用云函数做加法的简单运算
    wx.cloud.callFunction({
      name:'add',
    data:{
        a:4,
        b:3
    }
    })
    .then(res =>{
      console.log('运算成功',res)
    })
    .catch(err =>{
      console.log('运算失败',err)
    })
  1. 更新数据
update(){
  wx.cloud.database().collection('goods')
  .doc('14139e126104f72c013d08d63cc03ee1')
  .update({
    data:{
      price:10
    }
  })
  .then(res =>{
    console.log('修改成功',res)
   })
   .catch(err =>{
     console.log('修改失败',err)
   })
 }

在这里插入图片描述

//修改商品价格
newprice(){
  if(price==0 || price==''){
        wx.showToast({
          title: '价格不能为空',
          icon:'none'
        })
  }else{
  wx.cloud.callFunction({   //云函数更新商品价格
      name:'update',
      data:{
        id:id,
        price:parseInt(price)
      }
  })
  .then(res =>{
    console.log('调用云函数更新商品价格成功',res)
    wx.navigateTo({
      url: '/pages/demol/demol',
    })
    })
  .catch(err =>{
    wx.showToast({
      title: '更新商品价格失败',
      icon:'none'
    })
    
  })
}
}

云函数更新数据
在这里插入图片描述

  1. 删除数据
remove(){
  wx.cloud.database().collection('goods')
   .doc('2d44d6c26104fa20013f10c22ddd1194')
   .remove()
   .then(res =>{
    console.log('删除成功',res)
   })
   .catch(err =>{
     console.log('删除失败',err)
   })
 }
//删除商品
delete(){
  wx.showModal({
    title:'是否确认删除',
    content:'您再仔细想一想,是否真的要删除,删除后就再也找不回来了',
    success(res){
      if(res.confirm){
        wx.cloud.callFunction({
          name:'delete',
          data:{
            id:id
          }
          
        })
        .then(res =>{
          wx.navigateTo({
            url: '/pages/demol/demol',
          })
            
        })
        .catch(err =>{
          console.log('商品删除失败',err)
        })
      }else if(res.cancel){

      }
    }
  })
    
}

在这里插入图片描述

  1. 云函数分页
    在这里插入图片描述
<view wx:for="{{list}}" wx:key='id'>
    <view class="num">{{item.num}}</view>
</view>

getList(){
    wx.showLoading({
      title:'数据加载中...'
    })
    let len =this.data.list.length
      wx.cloud.callFunction({
        name:'fenye',
        data:{
          len:len,
          pageNum:30
        }

      })
      .then(res =>{
        wx.hideLoading()
        console.log('请求成功',res)
        let dataList=res.result.data
        if(dataList.length<=0){
           wx.showToast({
             title: '没有更多数据了',
             icon:'none'
           })
        }
        this.setData({
          list:this.data.list.concat(res.result.data)
        })
      })
      .catch(err =>{
        wx.hideLoading()
       console.log('请求失败',err)
     })



    
   
  }
  1. 查询数据
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  2. 判断两个数之间的区域

onLoad: function (options) {
    let db=wx.cloud.database().collection('goods')   //连接云开发数据库
    .where(db.command.and([
      {price:db.command.gt(5)},  //大于5
      {price:db.command.lt(10)}   //小于10
    ]))
    .get()
    .then(res =>{
      console.log('请求成功',res)
    })
    .catch(err =>{
      console.log('请求失败',err)
    })
  }
  1. 跳转页面并携带数据
goDatail(event){
      wx.navigateTo({
        url: '/pages/demol-1/demol-1?id='+event.currentTarget.dataset.id,
      })
   }
  1. 从表单获取用户输入的数据信息
    在这里插入图片描述

  2. 数据加载时的动画

wx.showLoading({    //数据加载时的动画
      title:'数据加载中...'
    })
  1. 页面上拉触底事件的处理函数
onReachBottom: function () {
    wx.showLoading({    //数据加载时的动画
      title:'数据加载中...'
    })
    let len =this.data.list.length
    wx.cloud.database().collection('num')
    .skip(len)
    .get()
    .then(res =>{
      wx.hideLoading()
      console.log('请求成功',res)
      let dataList=res.data
      if(dataList.length<=0){
         wx.showToast({
           title: '没有更多数据了',
           icon:'none'
         })
      }
      this.setData({
        list:this.data.list.concat(res.data)
      })
    })
    .catch(err =>{
      wx.hideLoading()  //隐藏数据加载时的动画
     console.log('请求失败',err)
   })
    
     
  }
  1. 页面刷新
<view wx:for="{{list}}" wx:key='id'>
<view bindtap="goDetail" data-id="{{item._id}}">
<image src="{{item.img}}" class="img"></image>
<text class="item">商品名:{{item.name}},价格:{{item.price}}</text>
</view>
</view>


页面相关事件处理函数--监听用户下拉动作
onPullDownRefresh: function () {
     wx.cloud.database().collection('goods')
    .get()
    .then(res =>{
        wx.stopPullDownRefresh()  //停止数据请求成功时的刷新动画
       this.setData({
         list:res.data
       })
    })
    .catch(err =>{
     console.log('请求失败',err)
   })
     
  }
  1. 开启刷新动画的事件
 wx.startPullDownRefresh()
  1. 文件的上传与下载
<button bindtap="chooseFile">选择文件</button>
请输入下载链接:
<input bindinput="getContent" class="download"></input>
<button bindtap="downloadFile">点击下载</button>

//上传文件第一步:选择 文件
chooseFile(){
   wx.chooseMessageFile({
        count:1,
        type:'all',
        success:res =>{
          console.log(res.tempFiles[0].name)
          let name= res.tempFiles[0].name
          let path=res.tempFiles[0].path
          this.uploadFile(name,path)
        }
   })
},
 //上传文件第二步:通过uploadFile上传选中的文件
 uploadFile(name,path){
    wx.cloud.uploadFile({
      cloudPath:name,
      filePath:path,
      success:res =>{
        console.log('上传成功',res)
        wx.cloud.downloadFile({
          fileID:res.fileID
        })
        .then(res =>{
        console.log('下载成功',res)
        wx.openDocument({
          filePath: res.tempFilePath,
          success:res =>{
            console.log('打开文档成功')
          }
        })
        })
        .catch(err =>{
         console.log('下载失败',err)
       })
      }
    })
 },
 //获取用户输入的下载链接
 getContent(e){
   console.log(e.detail.value)
   this.setData({
    fileId:e.detail.value
   })
 },
 //点击下载
 downloadFile(){
     let fileId=this.data.fileId
     console.log('点击下载',fileId)
     if(fileId!=null&& fileId.length>0){
      wx.cloud.downloadFile({
        fileID:fileId
      })
      .then(res =>{
      console.log('下载成功',res)
      wx.openDocument({
        filePath: res.tempFilePath,
        success:res =>{
          console.log('打开文档成功')
        }
      })
      })
      .catch(err =>{
       console.log('下载失败',err)
     })
     }else{
       wx.showToast({
         title: '下载链接不正确',
         icon:'none'
       })
        console.log('下载链接不正确')
     }
     
 }
  1. 云存储
<button bindtap="chooseImg" data-type="1">选择图片</button>
<button bindtap="chooseVideo" data-type="2">选择视频</button>
<image wx:if="{{showImg}}"  src="{{imgUrl}}"></image>
<video wx:if="{{showVideo}}"  src="{{videoUrl}}"></video>


 //图片选择
   chooseImg(event){
     type=event.currentTarget.dataset.type
     console.log('类型',event.currentTarget.dataset.type)
       wx.chooseImage({
         count: 1,
         sizeType:['original','compressed'],
         sourceType:['album','camera'],
         success:res =>{
          const tempFilePaths= res.tempFilePaths
          this.uploadFile(res.tempFilePaths[0],'云图片.jpg',type)
         }
        
      })
    },
    //上传图片的第二步,直接上传图片到云存储
    uploadFile(temFile,fileName,type) {
       wx.cloud.uploadFile({
         cloudPath:fileName,
         filePath:temFile,
         success:res =>{
           if(type==1){
            this.setData({
              imgUrl:res.fileID,
              showImg:true,
              showVideo:false
            })
           }else if(type==2){
            this.setData({
              videoUrl:res.fileID,
              showImg:false,
              showVideo:true
            })
           }
            console.log('上传成功',res)
           
         },
         fail: err =>{
          console.log('上传失败',err)
         }
       })
    },
     
    //选择视频
    chooseVideo(event){
      type=event.currentTarget.dataset.type
      wx.chooseVideo({
        sourceType:['camera','album'],
        maxDuration:60,  //60秒
        camera: 'back',
        success:res =>{
          console.log('视频选择成功',res.tempFilePath)
          this.uploadFile(res.tempFilePath,'云视频.mp4',type)
        }
      })
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南离火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值