天天看點

vue webapp 分享到微信好友及微信朋友圈

用模拟器試了好幾次,分享服務清單傳回的都是空數組,需要用真機測試,最終用真機測試正常

HbuilderX配置如下

vue webapp 分享到微信好友及微信朋友圈
  1. vue頁面的 script
import shareJS from "../request/share.js"
var shareUrl = '',      //分享連結
detail = {};
 document.addEventListener("plusready",function(){
   shareJS.service()
 }, false);
           
  1. vue分享頁面 methods
// 點選分享按鈕
        shareHref() {
            var ids = [
            {
                id: "weixin",
                ex: "WXSceneSession"
            },
            {
                id: "weixin",
                ex: "WXSceneTimeline"
            }],
                bts = [
                {
                    title: "發送給微信好友"
                },
                {
                    title: "分享到微信朋友圈"
                }];
                plus.nativeUI.actionSheet({
                    cancel: "取 消",
                    buttons: bts
                },function (e) {
                    var i = e.index;
                    if (i > 0) {
                        if (i > 0) {
                            shareJS.shareAction(ids[i - 1].id, ids[i - 1].ex,shareUrl,detail);
                        }
                    }
                })
        },
           
  1. 封裝的js share.js
import Vue from 'vue'
import { Toast } from 'vant'
Vue.use(Toast);
let Share = new Object();
var shares = null;
Share.service = function(){
    plus.share.getServices(function(s){
        shares={};
        for(var i in s){
            var t=s[i];
            shares[t.id]=t;
        }
        console.log(JSON.stringify(s));
    }, function(e){
        alert("擷取分享服務清單失敗: "+JSON.stringify(e));
    });
}
  /**
 * 分享操作
 */
Share.shareAction = function(id, ex,shareUrl,detail) {
    var s = null;
    if (!id || !(s = shares[id])) {
        Toast("無效的分享服務!");
        return;
    }
    if (s.authenticated) {
        console.log("---已授權---");
        shareMessage(s, ex,shareUrl,detail);
    } else {
        console.log("---未授權---");
        s.authorize(function() {
            shareMessage(s, ex,shareUrl,detail);
        }, function(e) {
            Toast("認證授權失敗");
        });
    }
}
    /**
 * 發送分享消息
 */
function shareMessage(s, ex,shareUrl,detail) {
    var msg = {
        href: shareUrl,
        title: detail.name,
        content: detail.name,
        thumbs: [detail.goods_image_text],
        pictures: [detail.goods_image_text],
        extra: {
            scene: ex
        }
    };
    s.send(msg, function() {
        Toast("分享成功!");
    }, function(e) {
        Toast("分享失敗!");
    });
}

export default Share;