天天看點

Taro+Vue3開發微信小程式的分享好友功能

1、背景:使用taro架構和vue3架構開發小程式,實作一個把pdf檔案直接分享給微信好友。

一開始看taro文檔了解有偏差,導緻分享出去的檔案是個app的小程式連接配接。如下圖

Taro+Vue3開發微信小程式的分享好友功能

 實作代碼如下:

onShareAppMessage: function () {
    Taro.showShareMenu({
      withShareTicket: true
      // 使用者點選右上角分享給好友,要先在分享好友這裡設定menus的兩個參數,才可以分享朋友圈
      // menus: ['shareAppMessage', 'shareTimeline']  
    });
  },

js:
       <nut-button
          shape="square"
          class="bg-primary button mb-md"
          style="padding: 24rpx 146rpx"
          open-type="share"  // 增加這個屬性才能轉發
          >分享至微信聊天</nut-button
        >
           

後續仔細檢視taro文檔, Taro 文檔,發現這種寫法是個頁面元件,轉發出去的是個小程式,無法單獨将檔案轉發。

2、實作檔案單獨轉發給好友:微信小程式下載下傳檔案和轉發檔案給好友總結_海海呐的部落格-CSDN部落格_小程式分享檔案到微信

代碼實作:

<nut-button
          shape="square"
          class="bg-primary button mb-md"
          style="padding: 24rpx 146rpx"
          @tap="shareFile"
          :class="{ 'button-disable': isShare }"
          >分享至微信聊天</nut-button
        >

shareFile() {
      if (this.isShare) {
        return false;
      }
      this.isShare = true;
      let that = this;
      const params = {
        startDateId: this.userValue.project.startDateId,
        endDateId: this.userValue.project.endDateId,
        fileType: 'pdf'
      };
      Taro.downloadFile({ // 先進行下載下傳,接口傳回後再分享檔案
        filePath: Taro.env.USER_DATA_PATH + `/${that.projectName}`,
        url: `${config.serverUrl[getAppEnv()]}/watson/report/generateReport/${
          this.userValue.project.enterpriseId
        }?${queryToString(params)}`,
        header: {
          'content-type': 'application/json',
          cookie: Taro.getStorageSync('cookieKey')
        },
        success(res) {
          if (res.statusCode === 200) {
            that.isShare = false;
            Taro.shareFileMessage({
              filePath: res.filePath,
              fileName: that.projectName,
              fail() {
                showToast('分享失敗');
              }
            });
          }
        },
        fail() {
          showToast('分享失敗');
        }
      });
    },
           

效果如下:

Taro+Vue3開發微信小程式的分享好友功能