先寫一個share.js 放在 utils
准備工作 需要weixin-js-sdk
npm install weixin-js-sdk
安裝好后可以使用一下兩種方式進行引入。
/* 使用CommonJs規范引入 */ const wx = require('weixin-js-sdk'); /* 使用ES6模塊引入 */ import wx from 'weixin-js-sdk';
直接上demo代碼
import {post} from "../api/http";//封裝的請求方式post get import wx from 'weixin-js-sdk' export const shareTitle = '測試'; export const shareUrl = '測試連接'; export const shareImg = '測試圖片'; export const shareDesc = '測試詳情'; /** *分享 * @param _this * @param shareTitle 標題 * @param shareUrl 鏈接 * @param shareImg 圖片 * @param shareDesc 描述
* 也可以傳入對象 把這個demo變成一個公共方法,主要是便於回調分享成功的方法 例如 export const option */
//舉例:
let option = {
shareTitle:this.datalist.name, // 分享標題
shareUrl: window.location.href,
shareImg:this.datalist.image,// 分享圖標
shareDesc:'我在#侑侑商城#發現一個非常不錯的商品,快來看看吧',
success: function () {
alert(分享成功) //特別說明一下 微信官方已經關閉了分享是否成功的判斷了 所以不管你是取消了還是分享了 都是返回success
},
error: function () {
}
//end
export const commonShare = (_this, shareTitle, shareUrl, shareImg, shareDesc) => { let url = window.location.href; let data = { url: url }; post('main/getShareSign',data).then(res => { if (res.signature !=''){ var data = res; wx.config({ debug:false, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。 appId: data.appId, // 必填,公眾號的唯一標識 timestamp: data.timestamp, // 必填,生成簽名的時間戳 nonceStr: data.nonceStr, // 必填,生成簽名的隨機串 signature: data.signature, // 必填,簽名,見附錄1 jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage"] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2 }); wx.ready(function () { wx.onMenuShareTimeline({ title: shareTitle, // 分享標題 link: shareUrl, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 imgUrl: shareImg, // 分享圖標 success: function () { // 用戶確認分享后執行的回調函數 _this.$vux.toast.text('分享成功!!!'); }, cancel: function () { // 用戶取消分享后執行的回調函數 _this.$vux.toast.text('取消分享!!!'); } }); wx.onMenuShareAppMessage({ title: shareTitle, // 分享標題 desc: shareDesc, // 分享描述 link: shareUrl, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 imgUrl: shareImg, // 分享圖標 type: "", // 分享類型,music、video或link,不填默認為link dataUrl: "", // 如果type是music或video,則要提供數據鏈接,默認為空 success: function () { // 用戶確認分享后執行的回調函數 _this.$vux.toast.text('分享成功!!!'); }, cancel: function () { // 用戶取消分享后執行的回調函數 _this.$vux.toast.text('取消分享!!!'); } }); }); } }).catch(err => { alert(err) console.log(err) }) };
然后進入頁面初始化的時候執行此方法(否則如用戶直接點分享到朋友圈或朋友是不會顯示圖片等等 相當於還沒有生效)
var shareTitle=this.goodsTitle; var shareUrl=this.url; var shareImg=this.GoodsImg; var shareDesc="簡介詳細"; commonShare(this, shareTitle, shareUrl, shareImg, shareDesc);//分享朋友圈和朋友
注意: 在微信瀏覽器內是不可以直接通過自定義按鈕調起微信分享到朋友圈或朋友的。所以一般微信內自定義按鈕分享都需要做引導 “點擊右上方分享到朋友圈或朋友”