使用框架:Vue.js、微信JS-SDK、HTML5+(HBuilder)
两种场景:微信生态右上角自定义分享、APP分享到微信
前提
在开发中,采用了HBuilder的打包功能,把vue的项目打包成了 webApp,在manifest.json配置相应SDK就能使用HTML5+提供的封装的功能
以下代码均在js文件中实现,.vue文件无法使用
1’ 获取分享的服务列表
const updateSerivces = () => {
if (!window.plus) {
return false;
}
plus.share.getServices(function(s) {
shares = {};
for (const i in s) {
const t = s[i];
shares[t.id] = t;
}
sweixin = shares['weixin'];
}, function(e) {
console.log(`获取分享服务列表失败:${e.message}`);
});
};
2’ 分享基础配置
const share = (srv, msg, button) => {
console.log('分享操作!');
if (!srv) {
console.log('无效的分享服务!');
return;
}
button && (msg.extra = button.extra);
// 发送分享
if (srv.authenticated) {
console.log('---已授权---');
doShare(srv, msg);
} else {
console.log('---未授权---');
srv.authorize(function() {
doShare(srv, msg);
}, function(e) {
console.log(`认证授权失败:${JSON.stringify(e)}`);
});
}
}
3’ 发送分享
const doShare = (srv, msg) => {
console.log(JSON.stringify(msg));
srv.send(msg, function() {
console.log(`分享到"${srv.description}"成功!`);
}, function(e) {
console.log(`分享到"${srv.description}"失败: ${JSON.stringify(e)}`);
});
};
4’ 分享网页
const shareWeb = (sharemsg) => {
if (!window.plus) {
return false;
}
const msg = {
type: 'web',
thumbs: ['/static/logo.png'],
href: sharemsg.href,
title: sharemsg.title,
content: sharemsg.content,
};
console.log('sweixin:', JSON.stringify(sweixin));
sweixin ? plus.nativeUI.actionSheet({
title: '分享网页到微信',
cancel: '取消',
buttons: buttons
}, function(e) {
(e.index > 0) && share(sweixin, msg, buttons[e.index - 1]);
}) : plus.nativeUI.alert('当前环境不支持微信分享操作!');
}
5’ 分享图片
const shareImage = (sharemsg) => {
if (!window.plus) {
return false;
}
const msg = {
type:'image',
};
msg.pictures=[sharemsg.url];
sweixin?plus.nativeUI.actionSheet({
title:'分享二维码到微信',
cancel:'取消',
buttons:buttons
}, function(e){
(e.index > 0) && share(sweixin, msg, buttons[e.index-1]);
}) : plus.nativeUI.alert('当前环境不支持微信分享操作!');
}