一、vue+ h5頁面如何分享;
1、安裝sdk
? ??????npm install weixin-js-sdk --save
2、引入?sdk
3、config接口注入權(quán)限
4、因?yàn)楹芏囗撁嬉{(diào)用,所以封裝了函數(shù)可以復(fù)用? ?以下是代碼
```
var wx_share = new Array(4);
wx_share[0] = window.location.href.split('#')[0] + "/static/image/cart/shareLogo.png";? // share_img 分享縮略圖圖片
wx_share[1] = window.location.href.split('#')[0]; // share_link? 分享頁面的url地址,如果地址無效,則分享失敗;
wx_share[2] = "零元制作優(yōu)質(zhì)廣告,一元收獲“萬+”流量,低投入,高回報(bào),宣傳無憂。";// share_desc
wx_share[3] = "GGGO廣告狗-推廣好幫手,制作無憂,一元起投";// share_title
import { wxShare } from '@/api/pages'
import wx from 'weixin-js-sdk'
export const weiXinShare = (shareUrl) => {
? wxShare({url: window.location.href.split('#')[0]+'#'+window.location.href.split('#')[1]})
? .then(res => {
? ? if (res.code === "0000") {
? //配置微信信息
? wx.config({
? ? // debug : true, // true:調(diào)試時(shí)候彈窗
? ? appId : res.data.appId, // 微信appid
? ? timestamp : res.data.timestamp, // 時(shí)間戳
? ? nonceStr : res.data.nonceStr, // 隨機(jī)字符串
? ? signature : res.data.signature, // 簽名
? ? jsApiList : [
? ? // 所有要調(diào)用的 API 都要加到這個(gè)列表中
? ? 'onMenuShareTimeline', // 分享到朋友圈接口
? ? 'onMenuShareAppMessage', //? 分享到朋友接口
? ? 'onMenuShareQQ', // 分享到QQ接口
? ? 'onMenuShareQZone', // 分享到QQ空間
? ? 'onMenuShareWeibo' // 分享到微博接口
? ? ]
? });
? wx.ready(function() {
? ? // 微信分享的數(shù)據(jù)
? ? var shareData = {
? ? ? "imgUrl" : wx_share[0], // 分享顯示的縮略圖地址
? ? ? "link" : window.location.href.split('#')[0] + 'static/html/redirect.html?vueRedirect=' + encodeURIComponent(shareUrl), // 分享地址
? ? ? "desc" : wx_share[2], // 分享描述
? ? ? "title" : wx_share[3], // 分享標(biāo)題
? ? ? success : function() {
? ? ? ? // 分享成功可以做相應(yīng)的數(shù)據(jù)處理
? ? ? ? let data = orderId
? ? ? ? this.$router.push({name: 'checkstand', query: { data }})
? ? ? },
? ? ? cancel : function() {
? ? ? ? // 用戶取消分享后執(zhí)行的回調(diào)函數(shù)
? ? ? ? // alert("分享取消22");
? ? ? ? let data = orderId
? ? ? ? this.$router.push({name: 'checkstand', query: { data }})
? ? ? }
? ? };
? ? wx.onMenuShareTimeline(shareData);
? ? wx.onMenuShareAppMessage(shareData);
? ? wx.onMenuShareQQ(shareData);
? ? wx.onMenuShareQZone(shareData);
? ? wx.onMenuShareWeibo(shareData);
? });
? wx.error(function(res) {
? ? // config信息驗(yàn)證失敗會(huì)執(zhí)行error函數(shù),如簽名過期導(dǎo)致驗(yàn)證失敗,
? ? // 具體錯(cuò)誤信息可以打開config的debug模式查看,也可以在返回的res參數(shù)中查看,
? ? //對(duì)于SPA可以在這里更新簽名。
? ? // alert("好像出錯(cuò)了??!");
? });
? ? } else {
? ? ? this.$message({
? ? ? ? showClose: true,
? ? ? ? type: 'error',
? ? ? ? message: res.msg
? ? ? })
? ? }
? });
}
```
當(dāng)然,這些都是微信支持的一些方法,很簡單,拿來使用就可以
在這個(gè)項(xiàng)目中主要是遇到的一個(gè)坑,項(xiàng)目是用vue寫的,微信會(huì)自動(dòng)截取url #后面的部分,導(dǎo)致分享所有的頁面都是首頁。
這個(gè)問題主要是要了解微信是什么時(shí)候把頁面的地址截取的,經(jīng)過反復(fù)測試,發(fā)現(xiàn)在頁面打開加載完后的鏈接已經(jīng)是截取了的,所以每次得到的鏈接自然就是不完整的。經(jīng)測試,在created鉤子函數(shù)鏈接是完整的,所以在分享頁面created函數(shù)獲取鏈接?并傳參,就可以解決此問題
created() {
? ? weiXinShare(window.location.href)
}