1.新建share.js文件
const util = require('./util.js')
export default {
data() {
return {
// 设置默认的分享参数
// 如果页面不设置share,就触发这个默认的分享
share: {
title: '', // 自定义标题
path: `/pages/index/index`, // 默认跳转首页
imageUrl: '' // 可设置默认分享图,不设置默认截取头部5:4
}
}
},
onShareAppMessage(res) { // 发送给朋友
console.log('------------------onShareAppMessage------------------')
const that = this
// 动态获取当前页面栈
const pageInfos = util.getCurrentPageInfo() || {}
let fullPath = pageInfos.fullPath
if (!fullPath.includes('channelSource')) {
fullPath = fullPath.includes('?') ? `${fullPath}&channelSource=${util.getChannelSource()}` : `${fullPath}?channelSource=${util.getChannelSource()}`
}
console.log('---------pageInfos-------------', pageInfos)
console.log('---------fullPath-------------', fullPath)
that.share.path = `${fullPath}`
return {
title: this.share.title,
path: this.share.path,
imageUrl: this.share.imageUrl,
success(res) {
console.log('success(res)==', res)
setTimeout(() => {
uni.showToast({
title: `分享成功`,
duration: 2000,
icon: 'none'
})
}, 0)
},
fail(res) {
console.log('fail(res)==', res)
setTimeout(() => {
uni.showToast({
title: `分享失败`,
duration: 2000,
icon: 'none'
})
}, 0)
}
}
},
onShareTimeline(res) { // 分享到朋友圈
const that = this
// 动态获取当前页面栈
const pageInfos = util.getCurrentPageInfo() || {}
const fullPath = pageInfos.fullPath
that.share.path = `${fullPath}`
return {
title: this.share.title,
path: this.share.path,
imageUrl: this.share.imageUrl,
success(res) {
console.log('success(res)==', res)
setTimeout(() => {
uni.showToast({
title: `分享成功`,
duration: 2000,
icon: 'none'
})
}, 0)
},
fail(res) {
console.log('fail(res)==', res)
setTimeout(() => {
uni.showToast({
title: `分享失败`,
duration: 2000,
icon: 'none'
})
}, 0)
}
}
}
}
2.util.js文件中新增方法
/**
* 获取当前页路由及其当前页url query参数
* 兼容微信小程序及H5
*/
const getCurrentPageInfo = () => {
const routes = getCurrentPages() // 获取当前打开过的页面路由数组
const curRoute = routes[routes.length - 1].route // 获取当前页面路由
// 在微信小程序或是app中,通过curPage.options
// 如果是H5,则需要curPage.$route.query(H5中的curPage.options为undefined)
const fullPath = routes[routes.length - 1].$page.fullPath
const curParam = routes[routes.length - 1].options || routes[routes.length - 1].$route.query // 获取路由参数
return { fullPath, curRoute, routes, curQuery: curParam }
}
3.main.js引入并使用
// 全局分享
// 小程序分享的封装
import share from './utils/share.js'
Vue.mixin(share)
4.支持在页面中重写"onShareAppMessage"生命周期
如果您基于自己的一些业务逻辑,需要更加自定义的实现逻辑,可以在页面中重写onShareAppMessage生命周期即可覆盖通过mixin监听的onShareAppMessage生命周期。