微信小程序云开发基础

云开发

云数据库
导入数据库
const db=wx.cloud.database()
获取数据
<button type="primary" bind:tap="getData">云开发--获取数据</button>

<view wx:for="{{dataobj}}">
{{item.user}} ---{{item.phonenumber}}
</view> 


 data: {
    dataobj:''
  },
  //获取数据
  getData(){
//根据id名

 db.collection("getlist").doc("9fe3c0fd664353d700d6003253cba8e2").get().then(res=>{
     this.setData({
        dataobj:res.data
      })
   console.log(res.data)
    })

//由where获取
   db.collection("getlist").where({
       user:"喵喵"
   }).get().then(res=>{
       this.setData({
           dataobj:res.data
       })
       console.log(this.data.dataobj)
       console.log(res.data)
   })

  },
添加数据

<button type="primary" bind:tap="addData">云开发--add数据</button>
  //添加数据
  addData(){
  wx.showLoading({
   title: '数据加载中...',
   mask:true
  })
  db.collection("getlist").add({
      data:{
          user:"萌萌",
          phonenumber:"13616327394",
          arr:['打游戏','吃饭饭']
      }
  }).then(res=>{
      console.log(res)
      wx.hideLoading()
  })
  },
  
  

添加表单到数据库

//必须加name
<form bindsubmit="btnSub">
    <input name="user" placeholder="请输入用户名"/>
    <input name="phonenumber" placeholder="请输入手机号"/>
    <textarea name="content" placeholder="请输入备注"/>
    <button type="primary" form-type="submit">提交</button>
    <button  form-type="reset">重置</button>
</form>
 //添加表单到数据库
  btnSub(res){
      console.log(res)  //res.detail.value
    //   var user=res.detail.value.user
    //   var phonenumber=res.detail.value.phonenumber
    //   var content=res.detail.value.content

      //es6解构
      var {user,phonenumber,content}=res.detail.value
      console.log(user,phonenumber,content)
      
      db.collection("getlist").add({
          data:{
              user:user,
              phonenumber:phonenumber
          }
      }).then(res=>{
          console.log(res.data)
      })
  }
更新数据
<button type="primary" bind:tap="updateData">更新</button>

updateData(){
    //小程序端只能用doc,云函数端可以使用云函数
    db.collection("getlist").doc("e8da08086643601700da9d322713a087").update({
        data:{
            user:"meng"
        }
    }).then(res=>{
        console.log(res)
    })
},
删除数据
 <input type="text" bindinput="myIpt" placeholder="请输入id"/>
 <button type="primary" bind:tap="deleteData">删除</button>
myIpt(res){
 var vlu=res.detail.value
 myVlu=vlu
},
//删除记录
deleteData(){
 db.collection("getlist").doc("e8da08086643601700da9d322713a087").remove().then(res=>{
     console.log(res)
 })
}
count与watch

count的使用

<button type="primary" bind:tap="getNums">查询个数</button>
getNums(){
    db.collection("getlist").count().then(res=>{
        console.log(res)
    })
}

在这里插入图片描述

watch

onLoad:function(options){
    this.getData();
    db.collection("getlist").watch({
        onChange:res=>{
            console.log(res.docs)
        },
        onError:err=>{
            console.log(err)
        }
    })
}

在这里插入图片描述

limit
db.collection("getlist").limit(3).orderBy("time").get().then(res=>{
    console.log(res)
})
command
const _=db.command

getData2(){
    db.collection("getlist")
    .where({
        hits:_.in([255,666]) //hits为数据库表中的字段
    })
    .get()
    .then(res=>{
        this.setData({
            data:res.data
        })
    })
}
getData2(){
    db.collection("getlist")
    .where({
       tabs:_.all(['数码','科技'])
    })
    .get()
    .then(res=>{
        this.setData({
            data:res.data
        })
    })
}
updata(){
    db.collection('getlist').doc('1111111111')
    .update({
        data:{
            // title:'小程序开发'
            hits:_.inc(5),
            hit:_.inc(-6)
        }
    }).then(res=>{
        console.log(res)
    })
}
setData(){
    db.collection('getlist').doc('11111111111')
    .update({
        data:{
            list:_.push(['aaa','bbb'])
        }
    })
}
setData(){
    db.collection('getlist').doc('11111111111')
    .update({
        data:{
            list:_.pop()
        }
    })
}
setData(){
    db.collection('getlist').doc('11111111111')
    .update({
        data:{
            list:_.unshift(['智能','新闻'])
        }
    })
}

删除第一个

setData(){
    db.collection('getlist').doc('11111111111')
    .update({
        data:{
            list:_.shift()
        }
    })
}
setData(){
    db.collection('getlist').doc('11111111111')
    .update({
        data:{
            list:_.pull(),
            tabs:_.push({
                each:['新世纪','实训'],
                position:3
            })
        }
    })
}
云函数
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db=cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  return await db.collection('getlist').get()
}
 /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
    wx.cloud.callFunction({
        name:'getData'
    }).then(res=>{
        console.log(res.result.data)
    })
    },
云存储
上传单张图片
<button type="primary" bind:tap="clickBtn">上传文件</button>

<image src="{{picUrl}}" mode=""/>
  clickBtn(){
        wx.chooseMedia({
         success:res=>{
             console.log(res)
             var filePath=res.tempFiles[0].tempFilePath
             this.cloudFile(filePath)
         }
        })

    },
    cloudFile(path){
    wx.showLoading({
      title: '上传中....',
    })
     wx.cloud.uploadFile({
         cloudPath:Date.now()+".jpg",
         filePath:path
     }).then(res=>{
         console.log(res)
         this.setData({
             picUrl:res.fileID
         })
         wx.hideLoading()
     })
    },

在这里插入图片描述

上传多张图片
clickBtn() {
    wx.chooseMedia({
        success: res => {
            console.log(res);
            var mediaFiles = res.tempFiles;
            if (mediaFiles.length > 0) { // 检查是否选择了文件
                mediaFiles.forEach((item, idx) => {
                    var fileName = Date.now() + "_" + idx;
                    this.cloudFile(fileName, item.tempFilePath); // 使用tempFilePath属性作为文件路径字符串
                });
            } else {
                // 提示用户选择文件
                wx.showToast({
                    title: '请选择文件',
                    icon: 'none'
                });
            }
        }
    });
},

cloudFile(filename, path) {
    wx.showLoading({
        title: '上传中....'
    });
    wx.cloud.uploadFile({
        cloudPath: Date.now() + ".jpg",
        filePath: path
    }).then(res => {
        urlArr.push(res.fileID);
        if (filePath.length == urlArr.length) {
            this.setData({
                urlArr
            });
        }
        wx.hideLoading(); // 在处理完上传逻辑后隐藏加载提示
    });
},

在这里插入图片描述

  • 14
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值