1.前言
在uniapp中我们需要使用到微信公众号的JSSDK,但是每次处理wx.config()、wx.ready()和wx.error()时都需要重新初始化,并且在config中error时,wx.ready()和wx.error()会同时执行,本篇文章将利用hooks封装JSSDK的config和其他函数。
2.封装hooks
2.1新建index.ts
2.2引入js和导出函数
import wx from "weixin-jsapi";
export default function useWechatPermissionHooks(jsapi: Array<string>) {
const url = window.location.href.split("#")[0];
let isSuccess = false;
let inited = false;
function initWxConfig(Fn: { ready: Function; error: Function }) {
console.log("isSuccess", isSuccess, "inited", inited);
if (inited == true) {
Fn.ready();
return;
}
uni.showLoading({
title: "加载中",
mask: true,
});
getApp()
.globalData.$http.get("/你的接口", { url })
.then((res: any) => {
// console.log(res);
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印
appId: res.result.appid, // 必填,公众号的唯一标识
timestamp: res.result.timestamp, // 必填,生成签名的时间戳
nonceStr: res.result.noncestr, // 必填,填任意非空字符串即可
signature: res.result.signature, // 必填,填任意非空字符串即可
jsApiList: jsapi, // 必填,随意一个接口即可
});
isSuccess = true;
wx.ready(function () {
console.log("ready", isSuccess);
if (isSuccess == false) return;
inited = true;
Fn.ready();
});
wx.error(function (err) {
isSuccess = false;
console.log("error", isSuccess);
Fn.error(err);
});
uni.hideLoading();
});
}
return { initWxConfig };
}
2.3 在你的页面添加hooks
<script setup>
const { initWxConfig } = useWechatPermissionHooks(["startRecord", "stopRecord", "translateVoice"]);
function clickHandler(){
initWxConfig({
ready: () => {
console.log("is ready");
//TODO
},
error: err => {
console.log("err:", err);
//TODO
},
})
}
</script>
3.功能逻辑
在事件监听函数中进行初始化授权,inited为false,如果再次触发函数则inited为true,调用initConfig的Fn.ready(),对应wx.ready()的回调函数。
在hooks中声明isSuccess,为微信的JSSDK解决config不正确导致wx.ready和wx.error同时执行的问题,error比ready先执行。
4.结语
可以在评论区讨论uniapp和微信JSDK相关问题,博主有空可以给予回答。