JS实用功能-6、Vue开发 添加微信分享功能(全局分享)

在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/,没有根据路由参数来配置。

完成上述操作之后,就可以在全局都用到分享功能了。

posted @ 2020-01-10 10:58  padding2020  阅读(3495)  评论(11编辑  收藏  举报
想了解更多的,大家也可以关注我的公众号:padding2020