ufutx-love-h5-public/src/plugins/wxShare.js

113 lines
3.2 KiB
JavaScript
Raw Normal View History

2026-04-02 18:12:53 +08:00
import wx from 'weixin-js-sdk'
import store from '@/store'
const base = {}
2026-04-16 13:47:32 +08:00
2026-04-02 18:12:53 +08:00
base.install = function(Vue, options) {
2026-04-16 13:47:32 +08:00
// 初始化微信配置(只执行一次)
Vue.prototype.$initWechatConfig = function() {
return new Promise((resolve, reject) => {
const configData = store.state.app.configData
if (!configData) {
console.error('微信配置数据为空')
reject('微信配置数据为空')
return
}
wx.config(configData)
wx.ready(() => {
console.log('微信 JS-SDK 配置成功')
resolve()
})
wx.error((err) => {
console.error('微信 JS-SDK 配置失败:', err)
reject(err)
})
})
}
// 分享配置方法
2026-04-02 18:12:53 +08:00
Vue.prototype.$shareList = function(imgUrl, link, desc, title) {
2026-04-16 13:47:32 +08:00
// 检查 wx 是否已配置
if (!wx) {
console.error('微信 JS-SDK 未加载')
return
}
let share_title = ''
const fromOpenid = localStorage.getItem('from_openid')
const storeInfo = store.state.app.info
if (!fromOpenid || fromOpenid.length < 20) {
2026-04-02 18:12:53 +08:00
share_title = ''
2026-04-16 13:47:32 +08:00
} else if (storeInfo && storeInfo.nickname && storeInfo.nickname.length > 4) {
share_title = storeInfo.nickname.substring(0, 4) + '..推送'
} else if (storeInfo && storeInfo.nickname) {
share_title = storeInfo.nickname + '推送'
2026-04-02 18:12:53 +08:00
} else {
2026-04-16 13:47:32 +08:00
share_title = ''
2026-04-02 18:12:53 +08:00
}
2026-04-16 13:47:32 +08:00
// 确保在 wx.ready 中执行分享配置
if (wx && typeof wx.ready === 'function') {
wx.ready(() => {
console.log('开始配置分享参数', { title, desc, link, imgUrl })
// 隐藏菜单项(可选)
wx.hideMenuItems({
menuList: [] // 为空表示不隐藏任何菜单
})
// 分享给朋友
wx.updateAppMessageShareData({
title: desc !== '欢迎和我预约' ? share_title + '《' + title + '》' : `${title}】商家预约`,
desc: desc,
link: link,
imgUrl: imgUrl,
success: function() {
console.log('分享给朋友成功')
},
cancel: function() {
console.log('分享给朋友取消')
}
})
// 分享到朋友圈
wx.updateTimelineShareData({
title: share_title + '《' + title + '》',
link: link,
imgUrl: imgUrl,
success: function() {
console.log('分享到朋友圈成功')
},
cancel: function() {
console.log('分享到朋友圈取消')
}
})
// 兼容旧版本(可选)
if (wx.onMenuShareAppMessage) {
wx.onMenuShareAppMessage({
title: share_title + '《' + title + '》',
desc: desc,
link: link,
imgUrl: imgUrl,
success: function() {
console.log('分享成功-旧版')
},
cancel: function() {
console.log('分享取消-旧版')
}
})
2026-04-02 18:12:53 +08:00
}
})
2026-04-16 13:47:32 +08:00
} else {
console.error('wx.ready 不可用,请确保微信 JS-SDK 已正确加载')
}
2026-04-02 18:12:53 +08:00
}
}
export default base