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

一、目标

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

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

三、小程序使用流程

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

相关推荐
子洋几秒前
LLM 原理 - 输入预处理
前端·人工智能·后端
女生寝室0388 分钟前
DiskSGenius Pro [6.0.1.1645][单文件汉化版] 下载
前端
前端老宋Running18 分钟前
别让你那 5MB 的 JS 文件把用户吓跑:React 代码分割(Code Splitting)实战指南
前端·javascript·react.js
小飞侠在吗42 分钟前
vue ref
前端·javascript·vue.js
悟能不能悟43 分钟前
在 Vue Router 4 中,如何设置base参数
前端·javascript·vue.js
Lovely_Ruby1 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·后端
kong@react1 小时前
react+ts项目,富文本开发(wangEditor)
前端·react.js·前端框架
重铸码农荣光1 小时前
AI First + Mobile First:用大模型重构下一代应用开发范式
前端·架构·llm
Lovely_Ruby1 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(二),前端项目的开发,对接后端
前端
willingtolove2 小时前
使用chrome修改请求参数重新发送请求
前端·chrome