# CustomEvent

# 开始

十分适合做分享功能。

global.js

// 分享首页
const shareHomepage = () => {
  const link = `${window.location.origin}/course`
  const shareConfig = {
    title: '跟小帮规划学财商知识',
    desc: '经济行情不好?小帮规划带你了解财商知识',
    link: link,
    imgUrl: 'https://course-static.xiaobangguihua.com/upload/9898c361-10c9-4b1e-8141-4d84ceae450d.png',
  }

  setWeixinShare(shareConfig)
}

// 分享笔记
const shareNote = ({ noteId, uniqueId, productTitle, shareCredits = false }) => {
  const link = `${window.location.origin}/course/note/landing/${uniqueId}/${noteId}?sourceType=h5wxshare`
  const desc = `【小帮规划】${productTitle}精选笔记`
  const shareConfig = {
    title: '我又完成一条投资笔记,专门分享给你',
    desc: desc,
    link: link,
    imgUrl: 'https://course-static.xiaobangguihua.com/upload/9898c361-10c9-4b1e-8141-4d84ceae450d.png',
    success: async function() {
      growingService.pageShare(this.link, this.title)
      if (shareCredits) {
        const { score = 0 } = await creditService.shareNote(uniqueId)
        if (score > 0) {
          Toast.show(`分享成功 +${score}积分`)
        }
      }
    },
    complete: function() {
      GlobalModalShare.hide()
    },
  }

  setWeixinShare(shareConfig)
}

window.addEventListener('xiaobang-wechat-share/homepage', e => {
  shareHomepage(e.detail)
})

window.addEventListener('xiaobang-wechat-share/note', e => {
  shareNote(e.detail)
})

页面的js

if (// 判断分享什么) {
  const event = new CustomEvent('xiaobang-wechat-share/note', {
    detail: {
    noteId: this.noteId,
    uniqueId: this.uniqueId,
    productTitle: this.productTitle,
    shareCredits: this.showShareButton,
    },
  })
	window.dispatchEvent(event)
} else {
  const event = new CustomEvent('xiaobang-wechat-share/homepage')
  window.dispatchEvent(event)
}

weixin.js

import weixinService from '@@/services/weixin'
import { device } from '@@/utils/userAgent'
import { getShareImageUrl } from '@@/utils/imageCrop'
import growingService from '@@/services/growing'

// 默认微信分享参数
const defaultShareConfig = {
  title: '小帮规划',
  desc: '小帮规划',
  link: `${window.location.origin}/course`,
  imgUrl: 'https://oss.xiaobangtouzi.com/[xiaobangzouti]2019-06-19:5d0a0a594a3c5.png',
  success: function() {
    growingService.pageShare(this.link, this.title)
  },
}

/**
 * 设置微信分享
 *
 * @param {object} shareConfig 分享参数
 */
export const setWeixinShare = async shareConfig => {
  if (device.isWeixin) {
    const signature = await weixinService.getWeixinSignature()
    const config = Object.assign({}, defaultShareConfig, shareConfig)
    config.imgUrl = getShareImageUrl(config.imgUrl)
    window.wx.config(signature)
    window.wx.ready(() => {
      window.wx.onMenuShareAppMessage(config)
      window.wx.onMenuShareTimeline(config)
    })
  }
}

// 预览图片
export const previewImage = (current, imageList) => {
  window.wx.previewImage({
    current: current, // 当前显示图片的http链接
    urls: imageList, // 需要预览的图片http链接列表
  })
}