uniapp realizes the sharing function of small programs

In general, it is written like this, but it feels too troublesome, and each page has to be written once

<template>
<view></view>
</template>
<script>
	export default {
		data() {
			return {}
		},
		onLoad() {},
		methods: {},
		// 分享给好友
		onShareAppMessage(res) {
			console.log(res);
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: 'title', //自定义分享标题
				path: 'path', // '/pages/...'分享页面路径(打开分享时进入页),以/开头
				imageUrl: '', //可设置默认分享图,不设置默认截取头部5:4
			}
		},
		// 分享朋友圈
		onShareTimeline(res) {
			console.log(res);
			return {
				//同上
			}
		}
	}
</script>
<style></style>

So here I encapsulated

 Encapsulate share.js code

export default {
	data() {
		return {
			//设置默认的分享参数
			//如果页面不设置share,就触发这个默认的分享
			share: {
				title: '',//自定义标题
				path: `/pages/index/index`,  //默认跳转首页
				imageUrl: '',  //可设置默认分享图,不设置默认截取头部5:4
			}
		}
	},
    onShareAppMessage(res) { //发送给朋友
		let that = this
		// 动态获取当前页面栈
		let pages = getCurrentPages(); //获取所有页面栈实例列表
		console.log(pages,'所有页面')
		let nowPage = pages[pages.length - 1]; //当前页页面实例
		// let prevPage = pages[pages.length - 2]; //上一页页面实例
		that.share.path = `/${nowPage.route}`
		return {
			title: this.share.title,
			path: this.share.path,
			imageUrl: this.share.imageUrl,
			success(res) {
				console.log('success(res)==', res);
				uni.showToast({
					title: '分享成功'
				})
			},
			fail(res) {
				console.log('fail(res)==', res);
				uni.showToast({
					title: '分享失败',
					icon: 'none'
				})
			}
		}
	},
	onShareTimeline(res) { //分享到朋友圈
	let that = this
		// 动态获取当前页面栈
		let pages = getCurrentPages(); //获取所有页面栈实例列表
		let nowPage = pages[pages.length - 1]; //当前页页面实例
		// let prevPage = pages[pages.length - 2]; //上一页页面实例
		that.share.path = `/${nowPage.route}`
		return {
			title: this.share.title,
			path: this.share.path,
			imageUrl: this.share.imageUrl,
			success(res) {
				console.log('success(res)==', res);
				uni.showToast({
					title: '分享成功'
				})
			},
			fail(res) {
				console.log('fail(res)==', res);
				uni.showToast({
					title: '分享失败',
					icon: 'none'
				})
			}
		}
	},
}

mount to main.js

// 全局分享
// 小程序分享的封装
import share from "./utils/share.js"
Vue.mixin(share)

In this way, the effect picture is as follows! ! !

uniapp compilation judgment

https://blog.csdn.net/weixin_41891519/article/details/104365609

Guess you like

Origin blog.csdn.net/weixin_53339757/article/details/129915087
Recommended