几行代码封装,让小程序云函数变为真正云函数,开发体验直接起飞

一、目标

像调用普通方法那样使用云函数。

二、效果演示(以电影查询小程序为例)

三、小程序使用流程

  1. 核心封装代码:在 utils 目录创建 cloudFunction.js 文件
javascript 复制代码
/**
 * 导入云函数
 * @param {String} name 云函数名
 * @returns {Promise} 返回云函数处理结果
 */
globalThis.importCloudFunction = function (name) {
  return new Proxy(
    {},
    {
      get(target, prop) {
        return async function (...args) {
          let res = await wx.cloud.callFunction({
            name,
            data: {
              method: prop,
              params: args,
            },
          });
          return res.result;
        };
      },
    }
  );
};
  1. 导入封装代码:在 app.js 引入 cloudFunction.js
arduino 复制代码
// app.js
import "./utils/cloudFunction.js";
  1. 前端使用:在需要用的地方导入方法
scss 复制代码
// 某个页面.js
const { method1,method2,method3 } = importCloudFunction("函数名");
​
Page({
  data: {},
  onLoad() {
      method1();
  },
});

四、云函数使用流程

  1. index.js 封装的代码
ini 复制代码
exports.main = async (event, context) => {
  globalThis.originInfo = { event, context };
  const { method, params = [] } = event || {};
  if (method) {
    return require("./handle")[method](...params);
  }
  return { ...originInfo };
};
  1. 在同级目录创建handle.js
javascript 复制代码
module.exports = {
    method1(a,b){
        return a;
    },
    method2(a,b){
        return b;
    },
}

五、小程序电影示例逻辑源代码片段

developers.weixin.qq.com/s/Az8Mo3m47...

相关推荐
Rsun045516 小时前
React相关面试题
前端·react.js·前端框架
Lao乾妈官方认证唯一女友:D6 小时前
通过plasmo的wallet扩展添加新钱包
javascript·web3·区块链
ALKAOUA6 小时前
力扣面试150题刷题分享
javascript·笔记
鹏多多.6 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter·ios·前端框架
LawrenceLan6 小时前
37.Flutter 零基础入门(三十七):SnackBar 与提示信息 —— 页面反馈与用户交互必学
开发语言·前端·flutter·dart
迪巴拉15256 小时前
基于Vue与Spring Boot+Open Cv的智慧校园考勤系统
前端·vue.js·spring boot
swipe6 小时前
JavaScript 对象与属性描述符:从原理到实战
前端·javascript·面试
&活在当下&6 小时前
Vue3 h函数用法详解
前端·javascript·vue.js