UniApp 添加微信小程序的分享功能

Title UniApp 添加微信小程序的分享功能
Framework UniApp
User wy8817399@vip.qq.com
Id 34
Created 1/24/26, 2:04 AM
Modified 1/24/26, 9:55 AM
Published Yes
Content

1、page.json中在要添加分享的页面的style下面增加两句话

"enableShareAppMessage": true,
"enableShareTimeline": true

 

2、在对应页面的<script>里添加

// 在 <script setup> 中直接定义分享函数
	const onShareAppMessage = (res) => {
	  if (res.from === 'button') {
		console.log(res.target)
	  }
	  return {
		title: 'title',
		path: '/pages/index/index',
	  }
	}
	
	// 如果需要分享到朋友圈
	const onShareTimeline = () => {
	  return {
		title: 'title',
		query: `q=${searchKeyword.value}`
	  }
	}
	
	// 在onLoad中启用分享菜单
	onLoad(() => {
	  // 显示转发按钮
	  uni.showShareMenu({
		withShareTicket: true,
		// 如果需要分享到朋友圈,添加以下配置
		// #ifdef MP-WEIXIN
		menus: ['shareAppMessage', 'shareTimeline']
		// #endif
	  })
	})