App.vue 3.26 KB
<template>
  <div id="app">
    <keep-alive>
      <!--这里是会被缓存的组件-->
      <router-view v-if="this.$route.meta.keepAlive" @getWxConfig="getWxConfig" />
    </keep-alive>
    <!--这里是不会被缓存的组件-->
    <router-view v-if="!this.$route.meta.keepAlive" @getWxConfig="getWxConfig" />
  </div>
</template>
<script>
import wx from 'weixin-js-sdk';
export default {
  mounted () {
  },
  methods: {
    getWxConfig (param) {
      let u = navigator.userAgent;
      let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      let url = "";
      let isWx = /MicroMessenger/i.test(window.navigator.userAgent);
      if(!isWx){
        // 非微信环境不进行分享配置
        return;
      }
      if (isIOS) {
        // console.log("苹果")
        url = window.location.href.split("#")[0]; //hash后面的部分如果带上ios中config会不对
      } else {
        url = window.location.href;
      }
      this.http.getWxConfig({
        url: url
      }).then((res) => {
        this.wxData = res?.data
        const { timestamp, appId, nonceStr, signature } = this.wxData

        wx.config({ // eslint-disable-line
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印
          appId: appId, // 必填,公众号的唯一标识
          timestamp, // 必填,生成签名的时间戳
          nonceStr: nonceStr, // 必填,生成签名的随机串
          signature: signature, // 必填,签名
          jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'], // 必填,需要使用的JS接口列表
          openTagList: ['wx-open-launch-weapp'] // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']

        });

        /* eslint-disable */

        wx.ready(function () {
          console.log('share ready')
          if (param) {
            wx.updateAppMessageShareData({
              title: param.title, // 分享标题
              desc: param.desc, // 分享描述
              link: param.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: param.imgUrl, // 分享图标
              success: function () {
                // 设置成功
                console.log('分享设置成功')
              },
              fail: function (err) {
                console.log('分享设置失败:', err.errMsg)
              }
            })
            wx.updateTimelineShareData({//分享朋友圈
              title: param.title, // 分享标题
              link: param.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: param.imgUrl, // 分享图标
              success: function () {
                // 设置成功
                console.log('分享设置成功')
              },
              fail: function (err) {
                console.log('分享设置失败:', err.errMsg)
              }
            })
          }

        });


      })
    },
  }
}
</script>
<style>
html,
body,
#app {
  height: 100%;
  color: #333333;
  font-size: 0;
}
p {
  margin: 0;
}
</style>