vue项目中如何使用百度三方分享

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a5252145/article/details/85126398

百度三方分享

今天项目中用到分享功能,正好是vue项目,本来想着在网上找下操作教程,结果找了半天,发现也没几个能用的,还一个比一个能吹,步骤没一点思绪,就一气之下自己着手摸索出来一个,还没写样式,但功能已经能用了。
效果图如下:
在这里插入图片描述

步骤

  1. 在百度分享官网下载代码:http://share.baidu.com/,如下:(我这里用的是图标式,一般选择浮窗式,因为浮窗式只有js,不用加载html)
    在这里插入图片描述
  2. 下载好之后,发现上半部分是html代码,下边是js代码,
  3. 项目分类(我这里使用的是vue-cli)
    3.1 如果是普通项目,把div放在html标签里就行了,js放在script标签里就好了
    3.2 这里是vue项目,
    新建一个vue文件,share.vue
<template>
  <div>
    <div class="bdsharebuttonbox">

      <!-- 以下链接和setShare()中的bdSelectMiniList属性相对应 -->
      <a href="#" class="bds_more" data-cmd="more"></a>
      <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
      <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
      <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a>
      <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a>
      <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    </div>
  </div>
</template>

<script>
export default {
  name: "share",
  data() {
    return {};
  },
  mounted: function() {
    const that = this;
    setTimeout(() => {
      that.setShare();
    }, 0);
  },
  methods: {
    setShare() {
      //分享相关代码
      window._bd_share_config = {
        common: {
          bdSnsKey: {},
          bdText: "",
          bdMini: "1",
          bdMiniList: false,
          bdPic: "",
          bdStyle: "1",
          bdSize: "24"
        },
        share: {},
        selectShare: {
          bdContainerClass: null,
          // 这里和html标签里链接相对应
          bdSelectMiniList: ["sqq", "qzone", "tsina", "renren","weixin"]
        }
      };
      const s = document.createElement("script");
      s.type = "text/javascript";
      s.src =
        "/static/api/js/share.js?v=89860593.js?cdnversion=" +
        ~(-new Date() / 36e5);
      document.body.appendChild(s);

      // 百度分享有自动销毁的逻辑,加这么一段代码   重新初始化就没问题了。
      if (window._bd_share_main) {
        window._bd_share_main.init();
      }
    }
  }
};
</script>

<style scoped>
.bdsharebuttonbox {
  width: 200px;
  height: 60px;
  line-height: 60px;
  background: #fff;
  border: 1px solid #666;
  position: fixed;
  bottom: 36px;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
</style>
html代码放在template的位置,js处理放在自己新建的setShare方法之中,

在mounted生命周期里去处理它,style写它的样式,这样做完之后发现,还不行!!!
q为什么?

因为这里还有一个跨域问题,自己的项目是在https域名上面,然而百度的js是在http域名上的,在https上引用http的js会报错。

解决方法:
  1. 需要下载一个插件,GitHub地址:https://github.com/hrwhisper/baiduShare
  2. 将下载插件放到项目的static静态文件目录下;
  3. 把倒数第三行代码:http://bdimg.share.baidu.com/ 这些前缀去掉。(因为路径要引用咱们下载好的api)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

处理好之后运行项目,发现分享就可以用了。

另外:百度分享有自动销毁的逻辑,所以当显示一次之后,就没有了,
要处理一下,在我们定义的setShare()方法中加一段代码: 
if(window._bd_share_main){
	window._bd_share_main.init();
}

在这里插入图片描述

重新初始化就没问题了。

猜你喜欢

转载自blog.csdn.net/a5252145/article/details/85126398