因为是全局的分享,所有以下操作在App.vue中实现。

  1. 安装weixin-js-sdk
npm i weixin-js-sdk -S
  1. 在js引入并使用
script>
// 引入
import wx from "weixin-js-sdk";
export default {
  name: "App",
  created () {
    //刷新回到首页
    if (this.$route.path !== '/') {
      this.$router.replace('/')
    }    
    //分享
    this.wxShare();
  },  
  methods: {   
    //分享的方法
    wxShare () {
      var url = encodeURIComponent(window.location.href.split("#")[0]);
      this.$http
        .post(
          "后端请求路径",
          { url }
        )
        .then((res) => {
          let data = res.data;
          wx.config({
            debug: false,
            appId: data.appId,
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList: [
              "onMenuShareTimeline",
              "onMenuShareAppMessage",
              "onMenuShareQQ",
              "onMenuShareWeibo",
              "onMenuShareQZone",
            ],
          });
        });
      wx.ready(() => {
        var shareData = {
          title: "标题...",
          desc: "描述...",
          link: "分享出去的链接地址(入口)",
          imgUrl:
            "分享出去的icon图标地址",  
          success: () => { },
        };
        wx.onMenuShareTimeline(shareData);
        wx.onMenuShareAppMessage(shareData);
        wx.onMenuShareQQ(shareData);
        wx.onMenuShareWeibo(shareData);
        wx.onMenuShareQZone(shareData);
      });
    },
  },
};
</script>

注意:
有时候分享出去的图标可能出现不显示的情况,
一种可能是图标太大,图标大小建议在200 * 200px,30kb左右;
还有一种可能是图片地址不对,所以尽量使用线上地址:eg:https://www.xxx.com/xxx/share.jpg
或者写成:imgUrl:require(‘…/assets/img/share.jpg’)。

Logo

前往低代码交流专区

更多推荐