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

一、目标

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

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

三、小程序使用流程

  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...

相关推荐
IT_陈寒20 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic21 小时前
SwiftUI 手势笔记
前端·后端
橙子家1 天前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518131 天前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州1 天前
CSS aspect-ratio 属性完全指南
前端
Pedantic1 天前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端
飘尘1 天前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈
一颗烂土豆1 天前
Meshopt 压缩深度解析,为什么它比 Draco 更快
前端·javascript·webgl
浏览器工程师1 天前
AI Agent 接浏览器任务,先别让它一路点到底
前端·后端