vue cli 微信分享相关设置
1.npm install weixin-js-sdk --save
2.在src文件夹下新建文件夹mixin
3.在mixin文件夹中新建share.js
share.js代码:
import wx from 'weixin-js-sdk';
export default {
methods: {
// 设置 隐藏/显示 右上角菜单
setIfShowOptionMenu(flag){
wx.ready(function() {
if(flag){
// 显示 右上角菜单
wx.showOptionMenu();
}else{
// 隐藏 右上角菜单
wx.hideOptionMenu();
}
});
},
// 设置分享config
shareConfig(config) {
console.log(config);
wx.config({
debug: config.debug,
appId: config.appId, // 必填,公众号的唯一标识
timestamp: config.timestamp, // 必填,生成签名的时间戳
nonceStr: config.nonceStr, // 必填,生成签名的随机串
signature: config.signature, // 必填,签名
jsApiList: config.jsApiList // 必填,需要使用的JS接口列表
});
},
// 设置分享文案
setShareData(shareData){
wx.ready(function() {
// 好友
wx.updateAppMessageShareData({
title: shareData.title, // 分享标题
desc: shareData.desc, // 分享描述
link: shareData.link, // 分享链接
imgUrl: shareData.imgUrl, // 分享图标
success: function() {
// 设置成功
}
})
// 好友
wx.onMenuShareAppMessage({
title: shareData.title, // 分享标题
desc: shareData.desc, // 分享描述
link: shareData.link, // 分享链接
imgUrl: shareData.imgUrl, // 分享图标
success: function() {
// 设置成功
}
})
// 朋友圈
wx.updateTimelineShareData({
title: shareData.title, // 分享标题
link: shareData.link, // 分享链接
imgUrl: shareData.imgUrl, // 分享图标
success: function() {
// 设置成功
}
})
// 朋友圈
wx.onMenuShareTimeline({
title: shareData.title, // 分享标题
link: shareData.link, // 分享链接
imgUrl: shareData.imgUrl, // 分享图标
success: function() {
// 设置成功
}
})
});
},
// 拍照或从手机相册中选图API
chooseIMG(){
return new Promise(function(resolve,reject){
wx.chooseImage({
count: 1,
success: function(_backData) {
wx.getLocalImgData({
localId: _backData.localIds[0],
success: function(_backData) {
upimgurl = (_backData.localData.toString().indexOf('data:image/') > -1) ? _backData.localData : "data:image/jpeg;base64," + _backData.localData;
resolve(upimgurl);
}
})
}
});
wx.error(function(_backData) {
console.log(_backData)
})
});
},
}
}
4.使用:
(1)App.vue中设置config:
<script>
import share from '@/mixin/share.js';
import {getJsConfig} from '@/api/api.js';
export default {
name: 'App',
mixins:[share],
mounted() {
//获取js_config
if(localStorage.getItem('token')){
getJsConfig({url:location.href.split('#')[0]}).then(res => {
this.shareConfig(res.data);
});
}
},
}
</script>
(2)组件中-隐藏/显示 右上角菜单:
<script>
import share from '@/mixin/share.js';
export default {
mixins:[share],
data() {
},
mounted() {
// 隐藏 右上角菜单
// this.setIfShowOptionMenu(false);
// 显示 右上角菜单
// this.setIfShowOptionMenu(true);
},
}
</script>
(3)分享文案设置:
<script>
import share from '@/mixin/share.js';
export default {
mixins:[share],
data() {
},
mounted() {
// 显示 右上角菜单
this.setIfShowOptionMenu(true);
this.setShareData({
title:'标题',
desc:'描述',
link:'url',
imgUrl:'分享图url',
});
},
}
</script>
(4)调用微信拍照或从手机相册中选图API:
<script>
import share from '@/mixin/share.js';
export default {
mixins:[share],
data() {
},
mounted() {
},
methods:{
fun() {
this.chooseIMG().then(res => {
console.log(res);
});
},
}
}
</script>