zishu's blog

zishu's blog

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

How to integrate Baidu Analytics into a Nuxt project?

After deploying a website, one of the most important things we care about is the traffic and its analysis. Baidu Analytics is a good choice in China, and its basic features are free.

You only need to include a piece of JavaScript code in the head section.

<!-- <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> -->

The above code is provided by Baidu Analytics and needs to be placed within the <head></head> tags.

However, in Nuxt, there is no traditional <head></head> section. So we need to make some modifications.

1. First, create a file named baidu.js in the /plugins directory of the root folder.#

// /plugins/baidu.js

export default ({app: {router}, store}) => {
  /* Perform PV tracking on each route change */
  router.afterEach((to, from) => {
    /* Increase the PV count */
    try {
      window._hmt = window._hmt || []
      window._hmt.push(['_trackPageview', to.fullPath])
    } catch (e) {
    }
  })
}

2. Configure the nuxt.config.js file#

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

Simply include the Baidu Analytics URL in the script section, following the corresponding characters.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.