Vue公眾號(hào)實(shí)現(xiàn)全局鎖粉
先封裝自定義url和微信分享函數(shù)
URL函數(shù)
function get_share_url(data) {
const need_location = location.origin + '/#' + data.path
const url_data = data.query
let url_params_str = ''
for (const name in url_data) {
//user_id為自定義字段,根據(jù)自己更改
if (name == 'user_id') {
continue
}
url_params_str += '&' + name + '=' + url_data[name]
}
const share_url = need_location + '?user_id=' + store.getters.userId + url_params_str
return encodeURI(share_url)
}
location的值大家可以單獨(dú)去console研究一下,還是很有點(diǎn)用的
微信分享函數(shù)
function wxshare_sdk(dataForWeixin) {
const location_href = window.location.href
const data_domain = location_href.split('#')[0]
// 調(diào)用后臺(tái)接口換取參數(shù)(需要傳入當(dāng)前的頁面地址)
get_wchat_config_req(data_domain)
.then(res => {
wx.config({
debug: false,
appId: res.data.appId,
timestamp: res.data.timestamp,
nonceStr: res.data.nonceStr,
signature: res.data.signature,
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone', 'updateAppMessageShareData', 'updateTimelineShareData']
})
wx.ready(function() {
wx.onMenuShareTimeline({
title: dataForWeixin.title ,
desc: dataForWeixin.desc,
link: dataForWeixin.link,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) { },
success: function success(res) {
console.log('已分享')
dataForWeixin.success && dataForWeixin.success()
},
cancel: function cancel(res) {
console.log('已取消')
dataForWeixin.fail && dataForWeixin.fail()
},
fail: function fail(res) {
dataForWeixin.fail && dataForWeixin.fail()
}
})
})
wx.error(function(res) {
console.log(JSON.stringify(res) + '微信驗(yàn)證失敗')
// alert(JSON.stringify(res)+"微信驗(yàn)證失敗");
})
})
.catch(res => {
alert('獲取微信配置信息失敗')
})
}
Vue路由 進(jìn)入時(shí)加載分享,main.js中使用
//引入上面兩個(gè)
import wechatSDK from '@/utils/wechat'
router.afterEach((to, from) => {
console.log(to.meta)
if (to.query.user_id ) {
//鎖粉接口調(diào)用
share_enter_log_req(to.query.user_id, to.query.goods_id || to.query.id || '')
}
if (!to.meta.shareDef) {
// 是否是自定義分享,如果自定義分享,在router->mate的參數(shù)里設(shè)置
const share_url = wechatSDK.get_share_url(to)
wechatSDK.wxshare_sdk({
title: to.meta.title || '****',
desc: to.meta.shareDesc || '****',
link: share_url,
img: to.meta.shareLogo || '****'
})
}
})
以上有兩個(gè)問題,如果頁面接口需要使用url數(shù)據(jù),必須自己去頁面重新定義分享的函數(shù)(第一個(gè))
希望大家多多交流...