锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

云开发学习笔记

时间:2023-02-26 01:30:00 pcb传感器进口201a75

文章目录

  • 学习资料
  • 云开发启动
  • 数据库基础
      • 1. 查询操作---get()
        • 1.1 查询条件--where()
        • 1.2 单条查询--doc()
      • 2. 数据库权限
    • 3. 添加数据--add
      • 4. 更新数据--update()
      • 5. 删除数据--update()
    • 4. 快捷键常用于小程序开发
    • 5. 升序和降序--orderBy()
    • 6. 查询数量--limit()
    • 7. skip()
    • 8. 导入导出数据库
  • Command
    • 1. 比较操作符
      • 1.1 gt -- 大于 || gte -- 大于等于
    • 2. 逻辑操作符
  • 云函数
    • 1. 云函数的初始化
    • 2. 新建云函数
    • 3. 云函数优势
  • 云存储
    • 1. 选择图片并上传到云存储
    • 2. 上传文件
    • 3. 选择视频上传到云存储
    • 4. 选择word和pdf上传到云存储
    • 5. 从云存储空间下载文件
    • 6. 打开新页面的文档
  • 下拉刷新
    • 1. 在 json 文件中配置
    • 2. 监控下拉刷新
    • 3. 请求到达数据后停止刷新
    • 4. 刚打开页面时,启动刷新
  • 加载列表的分页
  • 搜索功能
  • 常用图标获取网站
  • cms后台管理网页版


学习资料

学习笔记:https://xiaoshitou.blog.csdn.net/article/details/112391688?spm=1001.2014.3001.5502

云开发启动

app.js中的 onLaunch 初始化函数

wx.cloud.init({       env: 'cloud1-5gc3ghfz919f82d3'  //云开发环境id }) 

云开发文件:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/quick-start/miniprogram.html

数据库基础

选择云开发中的数据库

创建一个语或数字创建一个集合,而不是汉字

初始化

const db = wx.cloud.database() 

1. 查询操作—get()

// 传统数据 db.collection('goods').get({       // 请求成功       success(res) {         console.log要求成功,res);       },       fail(err) {         console.log要求失败, err);       }     })      // ES6 的简洁语法     db.collection('goods').get().then(res => {       console.log第二个请求成功, res);     }).catch(err => {       console.log要求失败, err);     }) 

在传统写法中this 指当前函数,箭头函数 this 指向的pages

1.1 查询条件–where()

db.collection('goods').where({       name: '苹果'     })     .get().then(res => {       this.setData({         list: res.data       })       console.log第二个请求成功, res.data);      }).catch(err => {       console.log要求失败, err);     }) 

1.2 单条查询–doc()

获取记录的数据,doc参数不能空,参数是一个id值

db.collection('goods').doc('d2fe6f20624ee579058c4bea0e74ab35')       .get()       .then(res => {         console.log查询单条成功, res.data);         this.setData({           good: res.data         })       })       .catch(err => {         console.log(查询失败, err);       }) 

2. 数据库权限

数据库 -> 数据权限

  • 只有创建者可读写:管理员创建了这些数据,普通用户无法读取
  • 所有用户都可以阅读:无论谁创建数据,每个人都可以阅读

3. 添加数据–add

const db = wx.cloud.database()      db.collection('goods')     .add({  // 添加数据       data: {         name: 车厘子,         price: '200'       }     })     .then(res => {       console.log(添加成功, res);     })     .catch(err => {       console.log(添加失败, err);     }) 

4. 更新数据–update()

修改数据库中存在的数据

修改数据必须给出修改条件 where 或者 doc 指定要修改的对象

wx.cloud.database().collection('goods')     .where({       name: '车厘子'     })     .update({       data: {         price: 100       }     })     .then(res => {       console.log(修改成功, res);     })     .catch(err => {       console.error(修改失败, err);     }) 

5. 删除数据–update()

结合删除数据 doc 删除单个数据

wx.cloud.database().collection('goods')     .doc('d2fe6f20624fdedb05c201a1430f2a76')  // 填写要删除的条件 _id     .remove() // 删除数据     .then(res => {       console.log(成功删除, res);     })     .catch(err => {       console.error(删除失败, err);     }) 

配合 wx.showModel() API 使用,删除前确认

wx.showMdal({
  title: '提示',
  content: '这是一个模态弹窗',
  success (res) {
    if (res.confirm) {
      console.log('用户点击确定')
    } else if (res.cancel) {
      console.log('用户点击取消')
    }
  }
})

4. 小程序开发常用快捷键

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ptKsWvmP-1650959729450)(image/c1.png)]

5. 升序和降序–orderBy()

wx.cloud.database().collection('goods')
    .orderBy("price",'asc')		//asc:升序,dec:降序
    .get()
    .then(res => {
      console.log('商品列表请求成功', res.data);
      this.setData({
        list: res.data
      })
    })
    .catch(err => {
      console.log('商品列表请求失败', err);
    })

6. 查询数量–limit()

wx.cloud.database().collection('goods')
    .limit(2)
    .get()
    .then(res => {
      console.log('商品列表请求成功', res.data);
    })
    .catch(err => {
      console.log('商品列表请求失败', err);
    })

7. skip()

从第几个数据开始读

wx.cloud.database().collection('num')
    .skip(2)
    .get()
    .then(res => {
      console.log('请求成功', res);
    })
    .catch(res => {
      console.log('请求失败', res);
    })

8. 数据库的导入导出

  • 导出:点击导出 -> 配置使用 JSON文件,选择位置 -> 用来备份
  • 导入:点击导入 -> 选择文件,冲突模式(insert, update) -> 注意:id 值不能有相同的

Command

官方文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/Command.html

1. 比较操作符

1.1 gt – 大于 || gte – 大于等于

lt() – 小于 、lte() – 小于等于 、 eq() – 等于 、 neq() – 不等于

gt

db.collection('goods')
    .where({
      price: db.command.gt(5)	// price > 5
    })
    .get()
    .then(res => {
      console.log('请求成功', res);
    })
    .catch(res => {
      console.log('请求失败', res);
    })

gte

db.collection('goods')
    .where({
      price: db.command.gte(5)	// price >= 5
    })
    .get()
    .then(res => {
      console.log('请求成功', res);
    })
    .catch(res => {
      console.log('请求失败', res);
    })

2. 逻辑操作符

and,or,not,nor

const _ = db.command
db.collection('goods')
      .where(_.and([{
          price: _.gt(3) // 大于3
        },
        {
          price: _.lt(20)  // 小于20
        }
      ]))
      .get()
      .then(res => {
        console.log('请求成功', res);
      })
      .catch(res => {
        console.log('请求失败', res);
      })

云函数

云函数即在云端(服务器端)运行的函数。在物理设计上,一个云函数可由多个文件组成,占用一定量的 CPU 内存等计算资源;各云函数完全独立;可分别部署在不同的地区。开发者无需购买、搭建服务器,只需编写函数代码并部署到云端即可在小程序端调用,同时云函数之间也可互相调用。

1. 初始化云函数

  • 创建一个文件夹 cloud 和pages 平行
  • 在 project.config,json 中配置云函数所在目录为 cloud
{
  "cloudfunctionRoot": "/cloud",
}

2. 新建云函数

右键 cloud 文件 -> 新建 Node.js 云函数

// 云函数入口文件
const cloud = require('wx-server-sdk')

// cloud.init()   如果这个错了,用下面最规范
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV  //常量指向当前云环境 id
})

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

调用云函数

wx.cloud.callFunction({
     name: 'getData'
})
.then(res => {
     console.log(res);
})
.catch(res => {
     console.log(res);
})

调用云函数获取 openid

wx.cloud.callFunction({
        name: 'getData'
      })
      .then(res => {
        console.log(res);
        this.setData({
          openid: res.result.openid
        })
      })
      .catch(res => {
        console.log(res);
      })

3. 云函数优势

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-semBCw2e-1650959729451)(image/c2.png)]

云存储

云存储就是可以用来存储视频,音频,图片,文件的一个云存储空间。如果你的小程序需要用到视频播放,音频播放,图片展示,文件上传与下载功能,就可以用到我们的云存储了。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-A5kzvJ1L-1650959729452)(image/c3.png)]

控制台可以很好的管理文件

1. 选择图片并上传到云存储

wx.chooseImage

官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success (res) {
    // tempFilePath可以作为img标签的src属性显示图片
    const tempFilePaths = res.tempFilePaths
  }
})

2. 上传文件

wx.uploadFile

官方文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/storage/uploadFile/client.uploadFile.html

wx.cloud.uploadFile({
  cloudPath: 'example.png',
  filePath: '', // 文件路径
  success: res => {
    // get resource ID
    console.log(res.fileID)
  },
  fail: err => {
    // handle error
  }
})

3. 选择视频上传到云存储

wx.chooseVideo(Object object)

官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseVideo.html

wx.chooseVideo({
  sourceType: ['album','camera'],
  maxDuration: 60,
  camera: 'back',
  success(res) {
    console.log(res.tempFilePath)
  }
})

4. 选择word和pdf上传到云存储

wx.chooseMessageFile(Object object)

官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseMessageFile.html

wx.chooseMessageFile({
  count: 10,
  type: 'image',
  success (res) {
    // tempFilePath可以作为img标签的src属性显示图片
    const tempFilePaths = res.tempFiles
  }
})

5. 从云存储空间下载文件

wx.cloud.downloadFile

官方文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/storage/downloadFile/client.downloadFile.html

wx.cloud.downloadFile({
  fileID: 'a7xzcb'
}).then(res => {
  // get temp file path
  console.log(res.tempFilePath)
}).catch(error => {
  // handle error
})

6. 新开页面打开文档

wx.openDocument(Object object)

官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.openDocument.html

wx.openDocument({
      filePath: filePath,
      success: function (res) {
        console.log('打开文档成功')
      }
    })

下拉刷新

1. 在 json 文件中配置

设置局部的下拉刷新

"enablePullDownRefresh": true,

2. 监听下拉刷新

onPullDownRefresh() {
    console.log('进行下拉刷新');
}

3. 请求到数据之后停止刷新

wx.stopPullDownRefresh()

4. 刚打开页面时启动刷新

// 启动刷新动画
wx.startPullDownRefresh()

列表的分页加载

主要使用 skip 和 limit 方法

  • skip:加载第几页的数据
  • limit:每页加载多少条
wx.cloud.database().collection('num')
      .skip(20 * page)
      .get()
      .then(res => {
        // console.log('请求成功', res.data);
        if(res.data.length <= 0) {
            wx.showToast({
              title: '没有更多数据了',
              icon: 'none'
            })
        }
        this.setData({
          list: [...this.data.list, ...res.data]
        })
      })
      .catch(res => {
        console.log('请求失败', res);
})

在上拉触底事件函数中 page++

onReachBottom: function () {
    this.setData({
      page: this.data.page + 1
    })
    this.getList(this.data.page)
}

显示和隐藏 loading 效果

// 显示加载
wx.showLoading({
      title: '加载中...',
    })
wx.cloud.database().collection('num')
  	 .skip(20 * page)
      .get()
      .then(res => {
      // 成功隐藏
        wx.hideLoading()
        // console.log('请求成功', res.data);
        if(res.data.length <= 0) {
            wx.showToast({
              title: '没有更多数据了',
              icon: 'none'
            })
        }
        this.setData({
          list: [...this.data.list, ...res.data]
        })
      })
      .catch(res => {
      // 失败也隐藏
        wx.hideLoading()
        console.log('请求失败', res);
})

搜索功能

Database.RegExp

如果是多个字段匹配,使用and,or进行匹配

构造正则表达式,仅需在普通 js 正则表达式无法满足的情况下使用

// 数据库正则对象
db.collection('todos').where({
  description: db.RegExp({
    regexp: 'miniprogram',	// 要搜索的内容
    options: 'i',	// 不区分大小写
  })
})

实例

const db = wx.cloud.database()
    db.collection('num').where({
      name: db.RegExp({
        regexp: "gi",	// 要搜索的内容
        options: 'i',	// 不区分大小写
      })
    })
    .get()
    .then(res => {
      console.log('请求成功', res);
    })
    .catch(res => {
      console.error('请求失败', res);
    })

常用图标获取网站

阿里巴巴矢量图库:https://www.iconfont.cn/

cms网页版管理后台

设置 -> 扩展功能 -> 内容管理 -> 开通

更多 -> 内容管理

注意事项

  • 一个云开发对应一个内容管理(cms)

  • cms中的内容模型会自动同步到云开发的数据库中

  • 云开发的数据库的集合不能同步到cms中的内容模型中,需要创建同样名字的集合和同样字段才能同步过来

的内容
options: ‘i’, // 不区分大小写
})
})


> 实例

const db = wx.cloud.database()
db.collection(‘num’).where({
name: db.RegExp({
regexp: “gi”, // 要搜索的内容
options: ‘i’, // 不区分大小写
})
})
.get()
.then(res => {
console.log(‘请求成功’, res);
})
.catch(res => {
console.error(‘请求失败’, res);
})


# 常用图标获取网站

阿里巴巴矢量图库:https://www.iconfont.cn/

# cms网页版管理后台

设置 -> 扩展功能 -> 内容管理 -> 开通

更多 -> 内容管理

> 注意事项

- 一个云开发对应一个内容管理(cms)


- cms中的内容模型会自动同步到云开发的数据库中


- 云开发的数据库的集合不能同步到cms中的内容模型中,需要创建同样名字的集合和同样字段才能同步过来



















锐单商城拥有海量元器件数据手册IC替代型号,打造电子元器件IC百科大全!

相关文章