关键
- 要使用原生组件button,设置属性为open-type=“share”
- 要使用原生方法onShareAppMessage来监听分享行为,进行自定义逻辑操作
具体实现
单页面实现
- 在template中定义button
- 在methods中定义方法onShareAppMessage
<template>
<button
open-type="share"
:data-obj="item"
class="operate-item"
>
<text>转发</text>
</button>
</template>
<script>
export default {
data(){
return {}
}
methods:{
onShareAppMessage(res) {
// 这里的res对应上面给button传的自定义数据data-obj,可打印出来看看
const data = res.target.dataset.obj;
return {
title: '自定义分享标题',
path: `pages/index/index?id=${data.id}`, // 被分享人点击进来的url,后面可接参数
imageUrl: data.src, // 自定义分享图片
success: () => {
console.log('分享成功');
},
fail: () => {
console.log('分享失败');
},
};
},
}
}
</script>
全局实现
单页面实现无非就是在methods中添加上一个钩子函数onShareAppMessage,那么要是想整个项目中都有这个钩子函数,自然就想到vue的mixin混合功能了
分为两步:
- 定义shares.js混合文件
- 在main.js中全局引入混合文件
// src/utils/share.js
export default {
onShareAppMessage(res) {
const data = res.target.dataset.obj;
return {
title: '分享',
path: `pages/index/index?id=${data.id}`,
imageUrl: data.src,
success: () => {
console.log('分享成功');
},
fail: () => {
console.log('分享失败');
},
};
}
};
// src/main.js
import Vue from 'vue';
import App from './App';
import share from './untils/share'
Vue.mixin(share);
全局混合后,在单页面中便不用再定义onShareAppMessage方法
注意
当在全局定义了onShareAppMessage方法后,要是在单页面再次定义了,单页面会覆盖全局的方法,就会导致自定义失败,但是全局中的方法还是会运行。
因此若是自定义失败的,可以看看编译后的代码中,onShareAppMessage方法里的内容是怎样的进行错误排查。