share-mixin.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /**
  2. * share-mixin — 统一分享逻辑
  3. * 处理:邀请码获取、分享配置、自动绑定邀请码
  4. *
  5. * 使用方式:
  6. * mixins: [shareMixin],
  7. * mounted/after data load:
  8. * this.setShareInfo('推荐阅读: ' + title, '/pages/article-center/article-detail?id=' + id)
  9. */
  10. import { getReferralCode, bindReferral } from '../utils/api.js'
  11. export default {
  12. data() {
  13. return {
  14. referralCode: '',
  15. shareTitle: '',
  16. sharePath: ''
  17. }
  18. },
  19. onLoad(options) {
  20. // 自动绑定:从分享链接进入时,绑定邀请码
  21. if (options && options.inviteCode) {
  22. this.autoBindInviteCode(options.inviteCode)
  23. }
  24. },
  25. methods: {
  26. /**
  27. * 设置分享信息(由各页面在数据加载完成后调用)
  28. */
  29. setShareInfo(title, path) {
  30. this.shareTitle = title
  31. this.sharePath = path
  32. this.loadReferralCode()
  33. },
  34. /**
  35. * 获取自己的邀请码
  36. */
  37. async loadReferralCode() {
  38. if (this.referralCode) return
  39. try {
  40. var res = await getReferralCode()
  41. if (res && res.code === 200 && res.data) {
  42. this.referralCode = res.data.referralCode || res.data.code || ''
  43. }
  44. } catch (e) {
  45. console.log('获取邀请码失败', e)
  46. }
  47. },
  48. /**
  49. * 自动绑定分享者的邀请码
  50. * 规则:如果用户已有邀请人,则忽略此邀请码
  51. */
  52. async autoBindInviteCode(code) {
  53. // 未登录时存 storage,登录后由 login 页面处理
  54. if (!uni.getStorageSync('token')) {
  55. uni.setStorageSync('inviteCode', code)
  56. return
  57. }
  58. // 已绑定过则跳过
  59. var bound = uni.getStorageSync('boundInviteCode')
  60. if (bound === code) return
  61. try {
  62. var res = await bindReferral(code)
  63. if (res && res.code === 200) {
  64. uni.setStorageSync('boundInviteCode', code)
  65. console.log('邀请码绑定成功', code)
  66. } else if (res && res.code === 400) {
  67. // 后端返回 400 表示已有邀请人,记录此 code 避免重复请求
  68. uni.setStorageSync('boundInviteCode', code)
  69. console.log('用户已有邀请人,跳过绑定', code)
  70. }
  71. } catch (e) {
  72. console.log('邀请码绑定失败', e)
  73. }
  74. },
  75. /**
  76. * 拼接完整分享路径
  77. */
  78. getSharePath() {
  79. if (!this.sharePath) return ''
  80. if (this.referralCode) {
  81. var sep = this.sharePath.indexOf('?') === -1 ? '?' : '&'
  82. return this.sharePath + sep + 'inviteCode=' + this.referralCode
  83. }
  84. return this.sharePath
  85. },
  86. /**
  87. * 分享按钮点击(用于统计等)
  88. */
  89. onShareTap() {
  90. console.log('分享按钮点击')
  91. }
  92. },
  93. onShareAppMessage() {
  94. if (!this.shareTitle || !this.sharePath) {
  95. return {
  96. title: '浠艾福 — 给全家的一站式幸福提案',
  97. path: '/pages/index/index'
  98. }
  99. }
  100. return {
  101. title: this.shareTitle,
  102. path: this.getSharePath(),
  103. imageUrl: ''
  104. }
  105. }
  106. }