最近使用uniapp 开发微信小程序的时候,有一个分享转发的需求。要每个页面都写一个 onShareAppMessage,这样冗余代码太多,vue的mixins是一个我感觉不错的方案,设置一个全局的分享,不多说上代码:
第一步:编写share.js文件
路径 src/mixins/share.js
export default {
data() {
return {
// 设置默认的分享参数
share: {
title: '这里是小程序的名字',
// 路径
path: '/pages/home/home',
imageUrl: '',
desc: '这是关于XXXXXXXXXXXXXXXXX的小程序',
content: ''
}
}
},
onShareAppMessage(res) {
return {
title: this.share.title,
path: this.share.path,
imageUrl: this.share.imageUrl,
desc: this.share.desc,
content: this.share.content,
success(res) {
uni.showToast({
title: '分享成功'
})
},
fail(res) {
uni.showToast({
title: '分享失败',
icon: 'none'
})
}
}
}
}
复制代码
第二步:在main.js文件中引入
import Vue from 'vue'
import App from './App'
// 引入
import share from './mixins/share.js'
Vue.config.productionTip = false
// 注入
Vue.mixin(share)
const app = new Vue({
...App
})
app.$mount()
复制代码
OVER(没错就是这么简单,结束了!!!)