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#
- In the
plugins
section:
plugins: [
{
src: '~/plugins/baidu'
}
],
- 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.