业务背景
由h5(vue2)开发的公众号,需要在页面首页菜单添加跳转到其他小程序的入口,入口位置及样式不固定,如图:
功能实现分析
使用微信提供的发放标签 wx-open-launch-weapp,按照官方文档来就行,比较麻烦的是样式问题,如果按照官方文档样式只能包裹在 <script type="text/wxtag-template"></script>中,
复杂一点的样式处理写起来比较鸡肋,而且单位换算很难保持和我们其他页面样式一致,要解决这个问题,先用正常的写法把页面写好,再利用绝对定位 遮住需要跳转的区域即可
具体组件实现
<template>
<!-- h5跳转其他小程序 -->
<!-- 利用绝对定位 遮住需要跳转的区域即可 -->
<wx-open-launch-weapp
class="open-weapp"
:username="item.appId"
:path="item.url"
@launch="launch"
@error="error"
>
<script type="text/wxtag-template">
<!-- 这里唤起小程序的点按区域 -->
<style>.mask{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;}</style>
<div class="mask"></div>
</script>
</wx-open-launch-weapp>
</template>
<script lang="ts">
import { Vue, Component, Prop, Emit } from 'vue-property-decorator'
@Component({
name: 'OpenWeapp'
})
export default class OpenWeapp extends Vue {
@Prop({
default() {
return {
iconType: '',
title: '',
color: '',
showIcon: '',
}
},
})
item!: string
@Emit('launch')
private launch(info) {
console.log('点击跳转', info)
}
mounted() {
this.wxConfigHandler()
}
error(err) {
console.log('跳转失败', err)
}
wxConfigHandler() {
window.wx.ready(function () {
console.warn('微信sdk调用ready')
})
window.wx.error(function (res) {
console.warn('微信sdk调用失败', res)
})
}
}
</script>
<style lang="less" scoped>
.open-weapp {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
</style>
获取公众号配置信息方法我放到项目初始化时调用了,方法参考如下:
// 初始化wxConfig
const initWxConfig = async () => {
const url = encodeURIComponent(location.href.split('#')[0])
await window
.$getRequest('/wx/jsapi/config.htm', { url }, { showError: false })
.then(({ data }: any) => {
const res = data
if (res.result === 'Success') {
const { appId, timestamp, nonceStr, signature } = res.map
window.wx.config({
appId,
timestamp,
nonceStr,
signature,
jsApiList: [],
openTagList: ['wx-open-launch-weapp'] // 需要使用的开放标签列表
})
}
})
}
ps:如果Vue报不能识别标签的错误,如:
添加一段代码一项配置项即可:
Vue.config.ignoredElements = [
'wx-open-launch-weapp'
]