zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Nuxt 项目中如何引入百度统计?

在部署網站之後,我們最關心的事情無異於訪問量以及對其的分析。國內的百度統計是一個不錯的選擇,基本的功能都是免費的。

只需要在 head 中引入一串 javascript 代碼即可。

<!-- <script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?xxxxxxxxxxxxxxxxxxx";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script> -->

上面是百度提供的統計代碼,需要放在 <head></head>中。

但是在 nuxt 中,沒有傳統的 <head></head> 。所以要對它進行一些處理。

1. 首先在根目錄下 /plugins 新建一個文件 baidu.js#

// /plugins/baidu.js

export default ({app: {router}, store}) => {
  /* 每次路由變更時進行pv統計 */
  router.afterEach((to, from) => {
    /* 告訴增加一個PV */
    try {
      window._hmt = window._hmt || []
      window._hmt.push(['_trackPageview', to.fullPath])
    } catch (e) {
    }
  })
}

2. 配置 nuxt.config.js 文件#

  1. plugins中:
plugins: [
  {
    src: '~/plugins/baidu'
  }
],
  1. head中:
head: {
  // ...
  link: [
    // ...
  ],
  script: [
    { src: 'https://hm.baidu.com/hm.js?xxxxxxxxxxxxxxxxxxx' }
  ]
},

在 script 中寫入百度統計提供的 url 即可,按照對應的字符。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。