/** * share-mixin — 统一分享逻辑 * 处理:邀请码获取、分享配置、自动绑定邀请码 * * 使用方式: * mixins: [shareMixin], * mounted/after data load: * this.setShareInfo('推荐阅读: ' + title, '/pages/article-center/article-detail?id=' + id) */ import { getReferralCode, bindReferral } from '../utils/api.js' export default { data() { return { referralCode: '', shareTitle: '', sharePath: '' } }, onLoad(options) { // 自动绑定:从分享链接进入时,绑定邀请码 if (options && options.inviteCode) { this.autoBindInviteCode(options.inviteCode) } }, methods: { /** * 设置分享信息(由各页面在数据加载完成后调用) */ setShareInfo(title, path) { this.shareTitle = title this.sharePath = path this.loadReferralCode() }, /** * 获取自己的邀请码 */ async loadReferralCode() { if (this.referralCode) return // 未登录时不请求邀请码(避免 500 报错弹窗和 401 跳转) if (!uni.getStorageSync('token')) return try { var res = await getReferralCode() if (res && res.code === 200 && res.data) { this.referralCode = res.data.referralCode || res.data.code || '' } } catch (e) { console.log('获取邀请码失败', e) } }, /** * 自动绑定分享者的邀请码 * 规则:如果用户已有邀请人,则忽略此邀请码 */ async autoBindInviteCode(code) { // 未登录时存 storage,登录后由 login 页面处理 if (!uni.getStorageSync('token')) { uni.setStorageSync('inviteCode', code) return } // 已绑定过则跳过 var bound = uni.getStorageSync('boundInviteCode') if (bound === code) return try { var res = await bindReferral(code) if (res && res.code === 200) { uni.setStorageSync('boundInviteCode', code) console.log('邀请码绑定成功', code) } else if (res && res.code === 400) { // 后端返回 400 表示已有邀请人,记录此 code 避免重复请求 uni.setStorageSync('boundInviteCode', code) console.log('用户已有邀请人,跳过绑定', code) } } catch (e) { console.log('邀请码绑定失败', e) } }, /** * 拼接完整分享路径 */ getSharePath() { if (!this.sharePath) return '' if (this.referralCode) { var sep = this.sharePath.indexOf('?') === -1 ? '?' : '&' return this.sharePath + sep + 'inviteCode=' + this.referralCode } return this.sharePath }, /** * 分享按钮点击(用于统计等) */ onShareTap() { console.log('分享按钮点击') } }, onShareAppMessage() { if (!this.shareTitle || !this.sharePath) { return { title: '浠艾福 — 给全家的一站式幸福提案', path: '/pages/index/index' } } return { title: this.shareTitle, path: this.getSharePath(), imageUrl: '' } } }