微信小程序云开发使用方法-1

2022年已经过了几天了,之前做过微信小程序,但是没使用过小程序提供的云开发功能,今天学习了云开发数据库的使用,做个笔记记录下。
在小程序创建项目的时候,勾选云开发,等项目创建好后,项目目录中会出现如下图所示的文件夹,这就代表项目已经开通了云开发,文件夹中有自动带的文件夹,可以删掉。
在这里插入图片描述
云开发在小程序编辑器中点击此处,就可以打开云开发控制台了。
在这里插入图片描述
打开控制面板后,我们看下数据库
在这里插入图片描述
红色框中是创建一个数据集合,创建好后在点击添加记录,每添加一个就是一个数据记录
在这里插入图片描述
等我们创建好数据后,在相应的js文件中引用数据

获取数据库

const db = wx.cloud.database()//调用默认云环境的数据库引用
const list = db.collection('list')//调取数据库集合

这里说明下:
1、db可以根据自己喜好来更改,我这里用的是文档上写的。
2、collection(‘list’)中的list是我们创建的数据集合的名称。

在这里插入图片描述

查询数据

.get() 查询单个数据或集合中多个数
db.collection("list").get({
       success:res=>{
        console.log(res)
         this.setData({
           dataObj:res.data
        })
     }
 })
.doc() 查询单个数据
db.collection('list').doc('单个数据的id').get().then(res => {
  // res.data 包含该记录的数据
  console.log(res.data)
})
.where()查询多个数据
db.collection("list").where({
      name:"李四"
    }).get()
    .then(res=>{
      this.setData({
        dataObj:res.data
      })
      console.log(res)
    })
ES6写法 then 回调
db.collection("list").get().then(res=>{
      this.setData({
        dataObj:res.data
      })
      console.log(res)
  })

新增/插入数据

.add()方法 往集合中插入一条数据
 addData(){
   wx.showLoading({
     title: '数据保存中',
     mask:true//提示框显示时,按钮不可点击
   })
  db.collection("list").add({
    data:{
      title:'测试新增标题',
      name:"汪峰",
      content:"测试新增的内容",
    }
  }).then(res=>{
    wx.hideLoading()
    console.log(res)
  })
 },

实际操作表单提交到数据库

在form中添加bindsubmit 事件(触发submit事件),按钮中添加form-type,可用事件分别为:submit提交表单,reset重置表单。

<form action="" bindsubmit="addBtn">
  <view>
    <input type="text" name="title" placeholder="请输入" class="ipt"></input>
  </view> 
  <view>
    <input type="text" name="name" placeholder="请输入" class="ipt"></input>
  </view>
  <view>
    <textarea name="content" placeholder="请输入" class="ipt"></textarea>
  </view>
  <button type="primary" form-type="submit">提交</button>
  <button type="primary" form-type="reset">重置</button>
</form>
 //ES6写法
addBtn(res){
	wx.showLoading({
     title: '保存中',
     mask:true
   })
    var resValue=res.detail.value
    db.collection("list").add({
      data:resValue
    }).then(res=>{
      wx.hideLoading()
      console.log(res)
    })
}

以上就是学习云开发数据库如何创建及引用,还有常用的插入、查询等知识。坚持每天学习新知识,后续持续更新!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值