1. 程式人生 > >vue專案中如何使用百度三方分享

vue專案中如何使用百度三方分享

百度三方分享

今天專案中用到分享功能,正好是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();
}

在這裡插入圖片描述

重新初始化就沒問題了。