uniapp 實(shí)現(xiàn)微信小程序的全局轉(zhuǎn)發(fā)給好友/分享到朋友圈的功能。主要使用 Vue.js 的 全局混入 概念。
下面直接上 實(shí)現(xiàn)步驟和代碼:
創(chuàng)建全局分享內(nèi)容文件
1、創(chuàng)建一個(gè)全局分享的 js 文件。示例文件路徑為:@/common/share.js,在該文件中定義全局分享的內(nèi)容:
export default {
data() {
return {
// 默認(rèn)的全局分享內(nèi)容
share: {
title: '全局分享的標(biāo)題',
path: '/pages/home/home', // 全局分享的路徑
imageUrl: '../../static/imgs/fenxiang-img.png', // 全局分享的圖片(可本地可網(wǎng)絡(luò))
}
}
},
// 定義全局分享
// 1.發(fā)送給朋友
onShareAppMessage(res) {
return {
title: this.share.title,
path: this.share.path,
imageUrl: this.share.imageUrl,
}
},
//2.分享到朋友圈
onShareTimeline(res) {
return {
title: this.share.title,
path: this.share.path,
imageUrl: this.share.imageUrl,
}
},
}引入并全局注冊(cè)該文件
2、在項(xiàng)目的 main.js 文件中引入該 share.js 文件并使用 Vue.mixin() 方法將之全局混入:
// 導(dǎo)入并掛載全局的分享方法 import share from '@/common/share.js' Vue.mixin(share)
下面來看一下全局的分享效果:

自定義頁(yè)面分享內(nèi)容
3、如果在特定頁(yè)面需要自定義分享內(nèi)容,也仍舊可以使用頁(yè)面的 onShareAppMessage()和 onShareTimeline()方法自定義分享的內(nèi)容,全局的分享會(huì)被頁(yè)面定義的分享內(nèi)容覆蓋。示例如下:
onLoad() {},
// 自定義此頁(yè)面的轉(zhuǎn)發(fā)給好友(已經(jīng)有全局的分享方法,此處會(huì)覆蓋全局)
onShareAppMessage(res) {
return {
title: '頁(yè)面分享的標(biāo)題',
path: '/pages/my/my',
imageUrl: '../../static/imgs/mylogo.png'
}
},
// 自定義頁(yè)面的分享到朋友圈
onShareTimeline(res) {
return {
title: '頁(yè)面分享的標(biāo)題',
path: '/pages/my/my',
imageUrl: '../../static/imgs/mylogo.png'
}
},注:onShareAppMessage() 和 onShareTimeline() 方法是和 onLoad , methods 等方法同級(jí)的。
到此這篇關(guān)于uniapp 實(shí)現(xiàn)微信小程序全局分享的示例代碼的文章就介紹到這了,更多相關(guān)uniapp 小程序全局分享內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!






