受欢迎的博客标签

微信小程序云开发(32)--小程序云函数-单个云函数实现增删改查功能

Published

本篇主要学习1个云函数多种方法的调用实现方法

一、实现步骤:

1、新建小程序页面 pages/cate/index,  pages/cate/add/index

2、打开云开发添加数据库cate

3、编写云函数admin.js 每次编辑完成都要上传部署,否则不生效


 
// 云函数入口文件
 

const cloud = require('wx-server-sdk')
 
 
 
cloud.init()
 
const db = cloud.database()
 
// 云函数入口函数-start
 
exports.main = async (event, context) => {
 
  switch (event.module) {
 
    case 'cate': {
 
      return cate(event)
 
    }
 
    default: {
 
      return '模块不存在'
 
    }
 
  }
 
}
// 云函数入口函数-end

//分类管理-start

async function cate(event){
 
  try {
 
    switch(event.action){
 
      case 'add':{
 
        return await db.collection('cate').add({data:event.params})
 
      }
 
      case 'delete': {
 
        return await db.collection('cate').where(event.map).remove();
 
      }
 
      case 'update': {
 
        return await db.collection('cate').doc(event.id).update({ data: event.params });
 
      }
 
      case 'query': {
 
        let limit = event.num || 1000;
 
        return await db.collection('cate').where(event.map).limit(limit).get();
 
      }
 
      default: {
 
        return '方法不存在'
 
      }
 
    }   
 
  } catch (e) {
 
    return e;
 
  }
 
}
//分类管理-end


 
 
 
//分类管理
 

4、编写通用JS类  /pages/util/util.js


 
/***弹窗提示
 
@params title 提示文字 time 打开时间秒 icon 显示图标[none,success]
 
*/
 
function tips(title = '', time = 1500, icon = 'none') {
 
  wx.showToast({
 
    title: title,
 
    time: time,
 
    icon: icon
 
  })
 
}
 
 
 
/***弹窗确认提示
 
@params title 标题 content 内容 callback 返回函数
 
*/
 
function confirm(content='', callback) {
 
   wx.showModal({
 
     title: '温馨提示',
 
     content: content,
 
     success: function(res){
 
       callback(res);
 
     }
 
   })
 
}
 
 
 
/***云函数请求
 
@params name 云函数名称 data 参数 {action:'请求方法名',map:'查询参数',params:'参数'} callback 返回函数
 
*/
 
function coludRequest(name,data,callback){
 
  wx.showLoading({title: ''})
 
  wx.cloud.callFunction({
 
    name:name,
 
    data:data,
 
    success: res => {
 
      wx.hideLoading();
 
      callback(res);
 
    },
 
    fail: err => {
 
      console.log(err);
 
      wx.hideLoading();
 
    }
 
  })
 
}
 
 
 
module.exports = {
 
  tips: tips,
 
  confirm: confirm,
 
  coludRequest: coludRequest
 
}

4、编写页面 pages/cate/index.wxml


 
<view class="container">
 
   <view class="top">
 
     <text>分类列表</text>
 
     <view class="btn fr" bindtap="add">添加分类</view>
 
   </view>
 
   <view class="list">
 
      <view class="item" wx:for="{{cateList}}" wx:key="{{index}}">
 
        <text>{{item.title}}</text> 
 
        <view class="fr">
 
            <view class="btn" bindtap="editCate" data-id="{{item._id}}">编辑</view>
 
            <view class="btn red" bindtap="deleteCate" data-index="{{index}}"  data-id="{{item._id}}">删除</view>
 
        </view>
 
      </view>
 
   </view>
 
</view>


 
// pages/cate/index.js
 
import { tips,confirm,coludRequest } from '../util/util.js' 
 
 
 
Page({
 
 
 
  /**
 
   * 页面的初始数据
 
   */
 
  data: {
 
    cateList:[]
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面加载
 
   */
 
  onLoad: function (options) {
 
      this.getCate();
 
  },
 
 
 
  add:function(){
 
     wx.navigateTo({
 
       url: '/pages/cate/add/index',
 
     })
 
  },
 
 
 
  //查询分类
 
  getCate:function(){
 
    var that = this;    
 
    coludRequest('admin', {module:'cate', action:'query', map:{}},function(res){
 
      that.setData({ cateList: res.result.data });
 
    })
 
  },
 
 
 
  //编辑分类
 
  editCate:function(e){
 
    var id = e.target.dataset.id;
 
    wx.navigateTo({
 
      url: '/pages/cate/add/index?id='+id,
 
    })
 
  },
 
 
 
  //删除分类
 
  deleteCate:function(e){
 
     var id = e.target.dataset.id;
 
     var index = e.target.dataset.index;
 
     var that = this; 
 
     confirm('确认删除该分类吗?',function(res){
 
      if (res.confirm){
 
        coludRequest('admin', {module:'cate', action:'delete', map: { _id: id } }, function (data) {
 
          tips('删除成功', 1200, 'success');
 
          setTimeout(res => {
 
            var list = that.data.cateList;
 
            list.splice(index, 1)
 
            that.setData({ cateList: list });
 
          }, 1200)
 
        })
 
      }
 
    })
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面初次渲染完成
 
   */
 
  onReady: function () {
 
 
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面显示
 
   */
 
  onShow: function () {
 
 
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面隐藏
 
   */
 
  onHide: function () {
 
 
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面卸载
 
   */
 
  onUnload: function () {
 
 
 
  },
 
 
 
  /**
 
   * 页面相关事件处理函数--监听用户下拉动作
 
   */
 
  onPullDownRefresh: function () {
 
 
 
  },
 
 
 
  /**
 
   * 页面上拉触底事件的处理函数
 
   */
 
  onReachBottom: function () {
 
 
 
  },
 
 
 
  /**
 
   * 用户点击右上角分享
 
   */
 
  onShareAppMessage: function () {
 
 
 
  }
 
})

5.编写分类增加页面 /pages/cate/add/index.wxml


 
<view class="container">
 
  <form class="form">
 
    <view class="input-item">
 
      <view class="title">标题</view>
 
      <view><input type="text" maxlength="15" bindinput="getTitle" value="{{title}}" placeholder="请输入分类标题" /></view>
 
    </view>
 
    <view class="pd3"><view class="btn" bindtap="submitAdd">确定</view></view> 
 
  </form>
 
</view>


 
// pages/cate/add/index.js
 
import { tips, confirm, coludRequest } from '../../util/util.js' 
 
Page({
 
 
 
  /**
 
   * 页面的初始数据
 
   */
 
  data: {
 
      id:'',
 
      title:''
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面加载
 
   */
 
  onLoad: function (options) {
 
    var pageTit = '添加分类';
 
      if(typeof(options.id)!='undefined'){
 
          this.setData({id:options.id});
 
          this.getCate(options.id);
 
          pageTit = '编辑分类';
 
      }
 
      wx.setNavigationBarTitle({ title: pageTit })
 
  },
 
 
 
  getTitle: function (e) {
 
    var val = e.detail.value;
 
    this.setData({title: val});
 
  },
 
 
 
  submitAdd:function(){
 
    if(this.data.title==""){
 
       tips('请输入分类');
 
       return false;
 
    } 
 
    if(this.data.id==""){
 
      coludRequest('admin', { module:'cate',action:'add', params: { title: this.data.title }},function(res){
 
        tips('分类添加成功')
 
        setTimeout(res => {
 
          wx.navigateTo({
 
            url: '/pages/cate/index',
 
          })
 
        }, 1200)
 
      })
 
    }else{
 
      coludRequest('admin', { module: 'cate', action:'update', id: this.data.id, params: {title: this.data.title }}, function (res) {          
 
         tips('分类修改成功')
 
         setTimeout(res => {
 
           wx.navigateTo({
 
             url: '/pages/cate/index',
 
           })
 
         }, 1200)
 
      })
 
    }
 
  },
 
 
 
  getCate:function(id){
 
    var that = this;
 
    coludRequest('admin', {module:'cate', action: 'query', map: {_id:id} }, function (res) {     
 
       that.setData({ title: res.result.data[0].title });
 
    })
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面初次渲染完成
 
   */
 
  onReady: function () {
 
 
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面显示
 
   */
 
  onShow: function () {
 
 
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面隐藏
 
   */
 
  onHide: function () {
 
 
 
  },
 
 
 
  /**
 
   * 生命周期函数--监听页面卸载
 
   */
 
  onUnload: function () {
 
 
 
  },
 
 
 
  /**
 
   * 页面相关事件处理函数--监听用户下拉动作
 
   */
 
  onPullDownRefresh: function () {
 
 
 
  },
 
 
 
  /**
 
   * 页面上拉触底事件的处理函数
 
   */
 
  onReachBottom: function () {
 
 
 
  },
 
 
 
  /**
 
   * 用户点击右上角分享
 
   */
 
  onShareAppMessage: function () {
 
 
 
  }
 
})