在Vue4.0開發微信公眾號的時候,需要做微信分享功能。這個功能其實還算簡單,具體的思路如下:
1.安裝微信JSSDK和Axios(axios是http請求插件)
2.向后台請求微信配置參數
3.初始化微信分享配置API
4.需要分享的地方引用配置
那么現在來實現:
安裝插件:
yarn add weixin-js-sdk
yarn add axios
安裝好插件之后,創建一個weixinApi.js文件,添加如下代碼:
import wx from 'weixin-js-sdk'; import Axios from "axios"; const ShareImpl = function (option) { //option是分享的配置內容*/ const url = window.location.href.split("#")[0]; window.console.log(url, JSON.stringify(option)); Axios.get('獲取參數配置路徑', { params: {url} }).then((response) => { wx.config({ debug: false, appId: response.data.AppId, timestamp: response.data.Timestamp, nonceStr: response.data.NonceStr, signature: response.data.Signature, jsApiList: [ 'updateAppMessageShareData', 'updateTimelineShareData', ] }); }).catch(error => { window.console.log(error); }); wx.ready(function () { wx.updateAppMessageShareData({ title: option.shareTitle, desc: option.shareDesc, link: option.shareUrl, imgUrl: option.shareImg }); wx.updateTimelineShareData({ title: option.shareTitle, desc: option.shareDesc, link: option.shareUrl, imgUrl: option.shareImg, }); }) /*}*/ } export {ShareImpl}
然后在main.js中引用該配置:
let url = window.location.href.split("#")[0]; if(url.indexOf('from') != -1){ url = window.location.href.split("?")[0]; } window.console.log(url + 'favicon.png'); ShareImpl({ shareTitle: '深圳XXX', shareDesc: '讓AIXXXXXXX', shareUrl: url, shareImg: url + 'favicon.png', });
分享的路徑是整個域下的路徑,比如 :http://xxx.xxxx.com/xxxx/,沒有根據路由參數來配置。
完成上述操作之后,就可以在全局都用到分享功能了。