uniapp 微信小程序 配置分享朋友和朋友圈
- 首先在小程序中配置微信分享,和微信朋友圈, onShareAppMessage, onShareTimeline 这两个API 和 onLoad 同级目录配置
- 在小程序每个页面都要设置这两个函数,修改内容比较心烦,不符合代码风格。可以通过mixins 混入的方式给每个页面设置分享的内容
- 在使用 mixins 的时候, 可以在全局混入, 也可以在每个页面中混入
方式1:
每个页面中混入的方式
// share.js
export default {
onShareAppMessage: function () {
const _this = this;
const tx_title = '123'
const bz_title = '456'
const shareTitle = this.urlPath == 'bizhi' ? bz_title : tx_title
return {
title: shareTitle,
desc: shareTitle,
path: `/pages/${this.urlPath}/index?active=${_this.active}`, // 路径,传递参数到指定页面。
}
},
/*分享朋友圈 */
onShareTimeline: function() {
const _this = this;
const tx_title = '123'
const bz_title = '456'
const shareTitle = this.urlPath == 'bizhi' ? bz_title : tx_title
return {
title: shareTitle,
}
},
}
// 设置分享的页面 每个需要分享的页面,都需要引入
import share from '../share/index.js'
export default {
mixins: [share],
}
方式2:
// share.js
export default {
data() {
return {
// 默认的全局分享内容
share: {
title: '123',
path: '/pages/index/index', // 全局分享的路径
imageUrl: '../../static/banner1.png', // 全局分享的图片(可本地可网络),如果不给图片,就会是当前页面的截图
}
}
},
// 定义全局分享
// 1.发送给朋友
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,
}
},
}
// main.js
import share from './pages/share/index.js'
import Vue from 'vue'
Vue.mixin(share)