# uni-app 微信小程序设置全局的分享
- 小程序要实现分享功能,在要实现分享功能的页面手动实现onShareAppMessage,每个页面都写不利于维护和代码臃肿,因此使用vue的mixins 设置一个全局的分享
1.创建share.js
export default {
data() {
return {
share:{
title: 'xxx小程序',
imageUrl:'https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg',
}
}
},
onShareAppMessage(res) { //发送给朋友
return {...this.share}
},
onShareTimeline(res) {//分享到朋友圈
return {...this.share}
},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2.全局使用,在main.js使用添加全局的
import share from 'common/share.js'
Vue.mixin(share)
1
2
2
TIP
tip来了,uni官方文档说参数要写path是必填字段,我测试的不填的话就默认分享出当前路由路径,然后wx开发者工具测试打开的是首页,但是真机测试是没问题的!
- path字段为空打开的就是分享出去的页面!没什么问题
- 第二个小技巧就是实现方法用的是
{...this.share}小用一下解构,这样不固定写死,对应页面如果data定义了share新加的key就可以直接使用,不需要再去页面内实现这两个方法。 - 第三个小技巧就是对于分享带参数,跳转到具体的问题详情页,文章详情页,可以先搞一个重定向页面,接受参数请求数据之后再跳转对应的详情页,这样比较方便无缝衔接列表跳转详情页的业务逻辑。
data() { //data里加入新定义参数
return {
share:{
title:"xxxx",
path:"pages/question/queRediect/queRediect",
},
}
}
// 在获取数据之后
.then(res=>{
this.share.title = res.master.title
this.share.path = share.path +"?id=" + res.master.id + '&isopen=' + res.master.isopen
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
这样就ok了