记录一个页面数据加载成功后通过回调再实现分享功能

138 阅读1分钟

在微信公众号页面中,想要分享出来的页面缩略图是该页面中的一个图片,微信分享的函数就应该在页面加载完成后执行,这里记录一个回调的方法,实现调分享时候数据已经加载完毕,并拿到了缩略图链接;

我是在created里面调方法加载数据的,传入一个id和一个匿名函数作为回调;

 created() {
 let id = this.$store.state.id || this.$route.params.id || goodsId;
     this.getDetail(id, () => {
        // 微信分享;
        let authUrl = window.location.href;

        let logoStr = this.thumbnailUrl
          ? this.thumbnailUrl
          : 'http://app.orthoday.com/img/logo.png';
        setTimeout(() => {
          WeChatShare(authUrl, {
            nameCn: '骨事通',
            shareDesc: this.name ? this.name : '商品详情',
            sharePic: logoStr,
          });
        }, 400);
      });
 }

关键一点就是return typeof def == 'function' && def();在请求完后进行回调;

 // 获取数据
    getDetail(Id, def) {
      this.$axios
        .get(`/SDSmart/weixin/goodsDetail?id=${Id}`)
        .then((res) => {
          if (res.data.code == 1) {
            this.goodsDate = res.data.result_data; //产品详情信息
            this.name = res.data.result_data.name; //分享时用的的产品名称
            this.thumbnailUrl = res.data.result_data.thumbnailUrl; //分享时用的的缩略图
            return typeof def == 'function' && def(); //判断回调函数并执行
          } else {
            this.$notify('获取失败:', res.data.message);
            return typeof def == 'function' && def();
          }
        })
        .catch((err) => {
          this.$notify('获取失败 err:', err.message);
          return typeof def == 'function' && def();
        });
    },