Vue3 uniapp小程序分享功能实现

2,209 阅读1分钟

1. 新建share.js文件

const shareSuccess = () => {
	uni.showToast({
		title: '分享成功'
	})
}

const shareFail = () => {
	uni.showToast({
		title: '分享失败',
		icon: 'none'
	})
}

export default {
	data() {
		return {
			// 默认的分享参数
			share: {
				title: '',
				path: '/pages/login/index', // 默认分享路径
				imageUrl: '', // 默认分享图片
				desc: '',
				content: ''
			}
		}
	},
	onShareAppMessage(res) {
		console.log('全局分享', res)
		let shareInfo = res.target ? res.target.dataset.shareinfo : this.share
		return {
			...shareInfo,
			success(res) {
				shareSuccess()
			},
			fail(res) {
				shareFail()
			}
		}
	},
	// 分享到朋友圈
	onShareTimeline(res) {
		let shareInfo = res.target ? res.target.dataset.shareinfo : this.share
		return {
			...shareInfo,
			success(res) {
				shareSuccess()
			},
			fail(res) {
				shareFail()
			}
		}
	},
}
  1. 引入并注入到main.js文件

image.png

到这一步已经可以全局分享,但可以针对特定的页面定制分享内容

  1. 特定页面使用

需要用到按钮,下面案例是调用接口后给链接添加参数

<button type="primary" open-type="share" :data-shareInfo='shareInfo'>点此分享邀请</button>

const shareInfo = ref({
		title: '活动分享',
		path: '/pages/login/register/invite', // 分享路径
		imageUrl: '', // 分享图片
		desc: '',
		content: ''
	})
        
shareInvite().then((res) => {
			const info = res.info
			const params = '?garage_invite_id=' + info.garage_invite_id + '&garage_name=' + info
				.branch_name + '&teller_name=' + info.teller_name
			shareInfo.value.path += params
			uni.hideToast()
		})