1.share.js
utils内定义分享js文件
export default {
data() {
return {
//设置默认的分享参数
share: {
title: '分享的标题',
path: '/pages/index/index',
imageUrl: '',
desc: '',
content: ''
}
}
},
methods:{
//未登录的拦截
notLogin(){
let path = getCurrentPages()[getCurrentPages().length-1].$page.fullPath.replace(/%2F/g, '/') //登录失效,记录当前页面路径
uni.setStorageSync('prevPath', path);
uni.redirectTo({
url:'/pages/user/login'
})
uni.showToast({
title: '请先登录!',
icon: 'none'
})
},
},
onLoad: function() {
//显示当前页面的转发按钮
wx.showShareMenu({
withShareTicket: true,
menus: ["shareAppMessage", "shareTimeline"]
})
},
onShareAppMessage(res) { //分享好友
console.log(res,this.share)
let path = ''
// if(this.share.path.indexOf('&share') === -1){
// path = getCurrentPages()[getCurrentPages().length-1].$page.fullPath.replace(/%2F/g, '/')
// } else {
path = this.share.path
// }
return {
title: this.share.title,
path: path+'?id='+this.uid,
imageUrl: this.share.imageUrl,
desc: this.share.desc,
content: this.share.content,
success(res) {
uni.showToast({
title: '分享成功'
})
if(this.posterShow){
this.posterShow = false
}
},
fail(res) {
uni.showToast({
title: '分享失败',
icon: 'none'
})
}
}
},
onShareTimeline(res) { //分享到朋友圈
return {
title: this.share.title,
path: this.share.path+'?id='+this.uid,
imageUrl: this.share.imageUrl,
desc: this.share.desc,
content: this.share.content,
success(res) {
uni.showToast({
title: '分享成功'
})
if(this.posterShow){
this.posterShow = false
}
},
fail(res) {
uni.showToast({
title: '分享失败',
icon: 'none'
})
}
}
},
}
2.main.js
//在main.js中引入
import share from '@/utils/share.js'
//全局注册一个 mixin,该 mixin 是从名为 `share` 的对象中导入的。
Vue.mixin(share)
3.组件内使用
//全局使用,各个页面自己的分享
onLoad() {
this.share = {
title: '新的分享标题',
path: '/pages/newPage/index',
imageUrl: 'https://example.com/new-share-image.jpg',
desc: '新的分享描述',
content: '新的分享内容'
}
}