微信小程序 - 云开发


结合微信小程序官方文档学习点击浏览

一、注意事项

1、一定得用appid,新建项目使用云配置
2、首次开启云开发,必须耐心等待,下一步即可
在这里插入图片描述
在这里插入图片描述3、云函数在编写完成之后,需要进行上传部署

4、components文件夹不是系统自带的,是所有自定义组件存放位置,自定义组件,即是对多次使用的代码进行封装,形成一个新的标签,如<HdView></HdView>,本篇没有涉及。项目源码有相关介绍。

5、页面项目
在这里插入图片描述
6、基础开发注重.wxml, .wxss, .json等页面布局的学习,而云开发注重.js和云函数编写调用,逻辑思维以及.wxml页面渲染的学习

7、涉及到云函数及数据库
在这里插入图片描述
在这里插入图片描述
8、云函数报错解决:
链接一

链接二

还有的就找度娘吧!!!

二、代码实操

1、项目
在这里插入图片描述
2、开始编写
编写前清空所有云函数,及index.wxml, index.wxss和其他图片
在这里插入图片描述
index页面
index.wxml

<!--index.wxml-->
<button class="btn" type="primary" bindtap="getData">点击获取</button>
<view wx:for="{{dataObj}}" wx:key="index">{{item.title}} - {{item.author}}</view>

<view>------------------------------------------------------</view>

<button class="btn" type="primary" bindtap="addData">添加数据</button>

<view>------------------------------------------------------</view>

<form bindsubmit="btnSub">
  <input name="title" placeholder="请输入标题"></input>
  <input name="author" placeholder="请输入作者"></input>
  <textarea name="content" placeholder="请输入内容"></textarea>
  <button type="primary" size="mini" form-type="submit">提交</button>
  <button type="default" size="mini" form-type="reset">重置</button>
</form>

index.wxss

/**index.wxss**/
input{border: 1px solid rgb(255, 123, 0);}
textarea{border: 1px solid rgb(255, 123, 0);}

index.js

//index.js

// 请求数据库
const db=wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataObj:""
  },

  // 查询
  getData:function(){
    // 连接数据库

    // .doc查询指定id
    // db.collection("demouser").doc("9bf625a55f16dde0003bf34d0b3765fb").get({
    //   success:res=> {
    //     console.log(res)
    //     this.setData({
    //       dataObj:res.data
    //     })
    //  }
    // })

    // demouser  数据库名
    // .where 条件
    db.collection("demouser").where({
      author:"作者"
    }).get({
      success:res=> {
        console.log(res)
        this.setData({
          dataObj:res.data
        })
     }
    })

    // 解决回调地狱
    // db.collection("").get().then(res=>{

    // })
  },

  // 添加
  addData:function(){
    wx.showLoading({
      title: '数据加载中',
      mask:true
    })
    // 连接数据库

    // demouser  数据库名
    // .add 添加
    db.collection("demouser").add({
      data:{
        author:"作者3",
        title:"测试标题",
        content:"测试内容"
      }
    }).then(res=>{
      console.log(res);
      wx.hideLoading({
        complete: (res) => {},
      })
    })
  },

  // 表单添加数据
  btnSub(res){
    console.log(res);
    // 001
    // var title=res.detail.value.title;
    // var author=res.detail.value.author;
    // var content=res.detail.value.content;

    // 002 解构
    // var {title,author,content}=res.detail.value;
    var resVlu=res.detail.value;
    console.log(title,author,content);

    db.collection("demouser").add({
      // data:{
      //   title:title,
      //   author:author,
      //   content:content
      // }
        data:resVlu
    }).then(res=>{
      console.log(res);
      wx.hideLoading({
        complete: (res) => {},
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})

页面效果
在这里插入图片描述
在这里插入图片描述
demo页面
demo.wxml

<!--pages/demo/demo.wxml-->
<button type="primary" bind:tap="updateData">更新记录</button>

<view>------------------------------------------------------</view>

<input placeholder="请输入id" bindinput="myIpt"></input>
<button type="primary" bind:tap="deleteData">删除记录</button>

<view>------------------------------------------------------</view>
<button type="primary" bind:tap="btnNum">查询个数</button>

<view wx:for="{{dataArr}}" wx:key="id">
  {{item.title}}
</view>

demo.js

// pages/demo/demo.js

// 请求数据库
const db=wx.cloud.database()

var myVal="";

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  // 更新
  // update

  // updateData(){
  //   db.collection("demouser").doc("3d23c0a05f16eb5e004d8d1e6f5206d4").update({
  //     data:{
  //       author:"新的作者",
  //       title:"新的标题",
  //       content:"新的内容",
  //       posttime:"2022-02-23"
  //     }
  //   }).then(res=>{
  //     console.log(res);
  //     wx.hideLoading({
  //       complete: (res) => {},
  //     })
  //   })


  // set  删除更改,谨慎使用

  updateData(){
    db.collection("demouser").doc("3d23c0a05f16eb5e004d8d1e6f5206d4").set({
      data:{
        author:"新的作者2",
        title:"新的标题2",
        content:"新的内容2",
        posttime:"2022-02-23"
      }
    }).then(res=>{
      console.log(res);
      wx.hideLoading({
        complete: (res) => {},
      })
    })
  },


  // 获取要删除的id 3d23c0a05f16eb5e004d8d1e6f5206d4
  myIpt(res){
    var vl=res.detail.value;
    console.log(vl);
    myVal=vl;
    console.log(myVal);

  },


  // 删除
  deleteData(){
      db.collection("demouser").doc(myVal).remove({
        
      }).then(res=>{
        console.log(res);
        wx.hideLoading({
          complete: (res) => {},
        })
      })
  },

  // 查询个数
  btnNum(){
    db.collection("demouser").count().then(res=>{
      console.log(res);
    })
  },

  // 查询
  getData(res){
    db.collection("demouser").get({
      success:res=> {
        console.log(res)
        this.setData({
          dataArr:res.data
        })
     }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData();
    // .watch 监听
    db.collection("demouser").watch({
      onChange: function(snapshot) {
        console.log('snapshot', snapshot)
      },
      onError: function(err) {
        console.error('the watch closed because of error', err)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
       
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

页面效果
在这里插入图片描述
在这里插入图片描述
demo2页面
demo2.wxml
在这里插入图片描述
demo2.js

// pages/demo2/demo2.js

// 请求数据库
const db=wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  // 各项查询条件 limit 限制查询数量; orderBy  排序;skip  过滤(分页)从第几个数据开始; field 想要的字段名
  getData(){
    db.collection("demouser").limit(3).skip(0).field({
      title:true,
      author:true
    }).orderBy("posttime","dasc").get().then(res=>{
      console.log(res);
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

页面效果
在这里插入图片描述
在这里插入图片描述
demo3页面
demo3.wxml

<!--pages/demo3/demo3.wxml-->
<button class="btn" type="primary" bindtap="getData">点击查询</button>

<view wx:for="{{dataList}}" wx:key="index">
  {{item.title}}-{{item.author}}
</view>

---------------------

<!-- 小程序端只能更新一条记录,云函数可以多条 -->
<button class="btn" type="primary" bindtap="updateData">点击更新</button>

demo3.js

// pages/demo3/demo3.js

// 请求数据库
const db=wx.cloud.database()
const _=db.command

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList:[]
  },

  // Command各项查询
  getData(){
    // db.collection("demouser").where({
    //   author:_.eq("张三"),
    //   age:_.gte(18) ,//大于等于
    //   height:_.lte(150), //小于等于
    //   salary:_.and(_.gte(1000),_.lte(2500)) //and区间单对象 or差不多
    // }).get().then(res=>{
    //   console.log(res);
    //   this.setData({
    //     dataList:res.data
    //   })
    // })


    // db.collection("demouser").where(
    //   // and区间多对象  or差不多
    //   _.and([
    //     {
    //       height:_.lte(150)
    //     },
    //     {
    //       age:_.gte(18)
    //     },
    //   ])
    // ).get().then(res=>{
    //   console.log(res);
    //   this.setData({
    //     dataList:res.data
    //   })
    // })

    db.collection("demouser").where({
      posttime:_.exists(true), //报错,试试切换模拟器高占比版本
      //对数组
      // 大小
      // tab:_.size(2)
      // 包含
      tab:_.all(['小程序'])

    }).get().then(res=>{
      console.log(res);
      this.setData({
        dataList:res.data
      })
    })

  },

  // Command各项更新
  updateData(){
    // db.collection("demouser").doc("f47f682c5f1705de004e64b0089d6f66").update({
    //   data:{
    //     // 增加字段值+5
    //     age:_.inc(5),
    //     // 删除字典
    //     hit:_.remove(),
    //     style:{
    //       color:"red",
    //       size:12
    //     }
    //   }
    // }).then(res=>{
    //   console.log(res);
    // })

    // 更新数组
    db.collection("demouser").doc("08e51e265f16e1e2003f3ab659873177").update({
      data:{
        // list:_.push(["aaa","bbb"])
        tab:_.push(["aaa","bbb"]),
        tab:_.push({
          each:["7878"],
          position:1
        }),
        tab:_.pop(),
        tab:_.unshift(["123"]),
        tab:_.shift(),
        // 移除
        tab:_.pull(["aaa"])
      }
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

页面效果
在这里插入图片描述
在这里插入图片描述
demo4页面 (涉及云函数)
demo.wxml

<!--pages/demo4/demo4.wxml-->
<view class="row" wx:for="{{dataList}}" wx:key="index" bind:tap="clickRow" data-id="{{item._id}}" data-idx="{{index}}">
  <view class="title">{{index+1}}{{item.title}}</view>
  <view>阅读量:{{item.hit}}</view>
</view>

demo4.wxss

/* pages/demo4/demo4.wxss */
.row{padding: 80rpx 30rpx; border-bottom: 2rpx solid #ccc;}
.row .title{font-size: 50rpx;}

demo4.js

// pages/demo4/demo4.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList:[],
    
  },

  // 调用云函数 如果无参数调用,采用默认值
  getData(num=5,page=0){
    wx.cloud.callFunction({
      name:"demoGetList",
      // 传给云函数的变量
      data:{
        num:num,
        page:page
      }
    }).then(res=>{
      console.log(res);
      var oldData=this.data.dataList;
      var newData=oldData.concat(res.result.data);
      this.setData({
        // 接收并保存后端传回来的数据
        dataList:newData
      })
    })
  },

  // 点击增加阅读量
  clickRow(res){
    console.log(res);
    // 获取id和index
    var {id,idx}=res.currentTarget.dataset;
    wx:wx.showLoading({
      title: '数据加载中...',
      mask:true
    })
    // 云函数更新操作
    wx.cloud.callFunction({
      name:"upHit",
      data:{
        id:id
      }
    }).then(res=>{
      console.log(res);
      // 接受新的后端数据
      var rowData=this.data.dataList;
      rowData[idx].hit+=1;
      // 重新渲染
      this.setData({
        dataList:rowData
      })

      
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 调用方法
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var page=this.data.dataList.length;
    console.log(page);
    this.getData(5,page)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

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

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

cloud.init()
const db=cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  // 接受前端传来的参数
  var num=event.num;
  var page=event.page;
  // 数据库名称 demouser
  return await db.collection("demouser").skip(page).limit(num).get();
}

再建一个云函数
在这里插入图片描述

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

cloud.init()
const db=cloud.database();
const _=db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  var id=event.id;
  return await db.collection("demouser").doc(id).update({
      data:{
        hit:_.inc(1)
      }
  })
}

分别上传部署

页面效果
在这里插入图片描述
在这里插入图片描述
demo5页面
demo5.wxml

<!--pages/demo5/demo5.wxml-->
<!-- 云存储 -->
<button type="primary" bindtap="clickBtn">上传文件</button>
<image src="{{picUrl}}"></image>

demo5.js

// pages/demo5/demo5.js
var filePath=[]
var urlArr=[]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    urlArr:[]
  },

  // 上传图片
  clickBtn:function(){
      wx:wx.chooseImage({
      count: 0,
      sizeType: [],
      sourceType: [],
      success: (res) => {
        console.log(res);
        // 单图
        // var filePath=res.tempFilePaths[0];
        // this.cloudFile(filePath);
        // 多图
        filePath=res.tempFilePaths;
        filePath.forEach((item,idx)=>{
          var filename=Date.now();
          filename=filename+"_"+idx;
          this.cloudFile(filename,item);
        })
      },
    })
    wx.showLoading({
      title: '上传中...',
    })
  },

  // 云存储函数
  cloudFile(filename,path){
      wx.cloud.uploadFile({
      cloudPath:filename+".jpg",
      filePath:path
    }).then(res=>{
      console.log(res);
      // 单图
      // this.setData({
      //   picUrl:res.fileID
      // })

      // 多图
      urlArr.push(res.fileID);
      console.log(urlArr);
      wx.hideLoading({
        success: (res) => {},
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

页面效果
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值