微信H5跳转到小程序

需求

  • 需要从微信的H5网页进入我们自己的小程序。

实现

  • 步骤,参见https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html官方文档去加载对应的开放标签。
  • 由于框架的问题,会导致在vue和react中,加载不出来该开放标签,所以需要做特殊处理。

react处理

  • 将开放标签的代码写成字符串,然后传给一个空的divdangerouslySetInnerHTML属性。
const createWeAppHtml = () => {
      return {
            __html: `<wx-open-launch-weapp
            id="launch-btn"
            username="gh_xxxxxxxx" // 这个是小程序的原始ID,直接去小程序的基本设置页面翻到最下面就能看到
            path="pages/index/index.html"
        >
            <template>
                <style>
                    .btn {
                        padding: 18px
                    }
                </style>
                <button class="btn">打开小程序</button>
            </template>
        </wx-open-launch-weapp>`
        }
}
<div className="btn" dangerouslySetInnerHTML={createWeAppHtml()}></div>

vue

  • 由于这个开放标签是支持动态加载的,所以只需要写成字符串然后动态的插入在对应的标签里面就可以了。react里面这样写应该也是可以的,不过既然官方提供了原生的插入htmlapi就没必要用dom操作。
Mounted() {
  const html = `
      <wx-open-launch-weapp
            id="launch-btn"
            username="gh_xxxxxxxx" // 这个是小程序的原始ID,直接去小程序的基本设置页面翻到最下面就能看到
            path="pages/index/index.html"
        >
            <template>
                <style>
                    .btn {
                        padding: 18px
                    }
                </style>
                <button class="btn">打开小程序</button>
            </template>
        </wx-open-launch-weapp>
  `;
  document.getElementById('slot-demo').innerHTML = html;
}
原文地址:https://www.cnblogs.com/aloneMing/p/13969339.html