背景:
在h5中我们经常会需要引用小程序的api,比如页面跳转。本文就来说说如何在h5中使用小程序的api。
具体使用步骤如下:
小程序:
<web-view :src="url" @load="showBar"></web-view>
url为嵌套的h5链接,可以加一些参数,比如扫码参数、业务参数。
h5:
(1)在index.html文件中引入相关js
<!-- 微信 JS-SDK 如果不需要兼容小程序,则无需引用此 JS 文件。 -->
<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<!-- uni 的 SDK,必须引用。 -->
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
(2)在vue文件mounted中引入如下:
this.$nextTick(() => {
// 初始化uni.webview
document.addEventListener('UniAppJSBridgeReady', function () {
console.log('初始化uniapp的API成功');
/* eslint-disable*/
uni.getEnv(function (res) {
console.log('当前环境:' + JSON.stringify(res));
});
});
});
(3)这样就可以使用小程序的api了,提供的api如下:
实例:
h5中调用小程序的接口方法其实和h5中调用接口的方法相同。例如:在h5中检测用户的登录状态,需要吊起微信登录页面。具体步骤如下: (1)首先判断用户的微信登录状态,调用小程序的登录接口。
this.service.get('/wxserver/user/getuserstatus', params, true).then((res) => {
this.isLogin = res.data.status !== 0;
});
(2)如果未登录,则跳转到微信的登录页面B,否则跳转到小程序的另一个页面C 登录页面B:
uni.navigateTo({ // 跳转到登录页
url: '/pagesB/wxbind/wxbind?jumpUrl=' + encodeURIComponent('/pagesB/course/short-course-playback'),
fail: (error) => {
console.log('error;', error);
}
});
页面C:
uni.navigateTo({
url: courseDetail,
fail(err) {
console.log('失败', err);
}
});