foreword
In "An article that takes you to build a blog with VuePress + Github Pages" , we used VuePress to build a blog, click to view the final effect: TypeScript4 Chinese document . Today we add data statistics function to the blog.
1. Baidu Statistics
1.1 Create a site
1.1.1 Login to the site
Login to Baidu Statistics background: https://tongji.baidu.com/web/welcome/login
1.1.2 Add a new website
In "Administration" - "Site List", click "Add Site":
1.1.3 Fill in the information
Add website domain name, website homepage and other information:
1.1.4 Get the code
After adding, it will automatically jump to the code acquisition page. We can see the monitoring code generated based on the site information we filled in. Note that this code is specially marked. You need to generate and use it according to your own site information:
1.2 Import code
We write the generated code config.js
module.exports = {
head: [
[
'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>
`
]
]
}
1.3 Verification
1.3.1 Local Authentication
We run locally, refresh the page, and see the page request:
You can see that the page requested hm.js
and hm.gif
, indicating that the request was indeed sent.
1.3.2 Online verification
Now we deploy it online. After the deployment is completed, we can also automatically detect or manually detect the code installation Code Installation Check
1.4 Wait
If the code is installed correctly, typically after 20 minutes, you can view website analytics data.
2. Statistics of single-page applications
2.1 Question
We head
. If it is an ordinary page, there is no problem, but we use VuePress to build a single-page application. During the page switching process, the page will not be reloaded, and Baidu statistics will not be triggered. . So we can only count the pages that users visit, but we don't know which articles have been clicked and which routes have been jumped to. In order to achieve data statistics during route switching, we also need to monitor route changes and report data manually. What should we do?
2.2 Ideas
First, according to the introduction of VuePress official website
A VuePress website is a single page application Vue , Vue Router and webpack
In the basic configuration of the VuePress document, a application-level configuration :
Since VuePress is a standard Vue application, you can.vuepress/enhanceApp.js
file, which will be imported into the application when it exists.enhanceApp.js
shouldexport default
a hook function that accepts an object containing some application-level properties as a parameter. You can use this hook to install some additional Vue plugins, register global components, or add additional routing hooks, etc:
// 使用异步函数也是可以的
export default ({
Vue, // VuePress 正在使用的 Vue 构造函数
options, // 附加到根实例的一些选项
router, // 当前应用的路由实例
siteData, // 站点元数据
isServer // 当前应用配置是处于 服务端渲染 或 客户端
}) => {
// ...做一些其他的应用级别的优化
}
Here we can see that there is a routing instance router that provides the current application, because the routing of VuePress is driven by Vue Router, so we check the introduction of the official website of Vue Router, we can see a global front guard :
You can use router.beforeEach to register a global front guard:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
Each guard method receives three parameters:
- to: Route: the target route object to be entered
- from: Route: The route that the current navigation is leaving
- next: Function: Be sure to call this method to resolve this hook.
From this, we can register a global front guard to listen for route changes after obtaining the routing instance.
Now that we can monitor route changes, how can we manually report data? For this, we can check the document , which talks about how to call the PV tracking code in JS for this single-page application:
_hmt.push(['_trackPageview', pageURL]);
// pageURL:指定要统计PV的页面URL。此项必选。
Now that everything is in place, let's start writing.
2.3 Practice
We create a new .vuepress
enhanceApp.js
folder and write the code:
export default ({ router }) => {
router.beforeEach((to, from, next) => {
if (typeof _hmt !== "undefined") {
if (to.path) {
_hmt.push(["_trackPageview", to.fullPath]);
}
}
next();
});
};
Now we run the code locally, and then click on the article, including clicking on the anchor point in the article, and check the request to see the reported data.
2.4 Carding
Here we sort out the situations in which data can be reported:
- Page entry and refresh
- Click on other articles, routing switch
- Click the article anchor to switch to other chapters (this is actually a routing switch)
Now the above will trigger data reporting.
3. Google Statistics
VuePress directly provides the @vuepress/plugin-google-analytics
plug-in. Using this plug-in, we do not need to manually monitor routing changes. Data reporting will be triggered in the three situations mentioned in the previous section.
We directly refer to the document :
3.1 Installation
yarn add -D @vuepress/plugin-google-analytics
# OR npm install -D @vuepress/plugin-google-analytics
Note: If your project is using the Google analytics plugin, it is recommended to use Yarn (opens new window) instead of npm to install all dependencies. Because in this case npm will generate the wrong dependency tree.
3.2 Use
module.exports = {
plugins: [
[
'@vuepress/google-analytics',
{
'ga': '' // UA-00000000-0
}
]
]
}
3.3 Get ga
3.3.1 Log in to the background
The so-called ga, the Google Analytics ID, we need to go to the Google Analytics creation site to obtain:
We log in to the Google Analytics backend: https://analytics.google.com/
If you log in for the first time, you will follow the instructions to create an account. The so-called account is usually a company or organization.
3.3.2 Adding media resources
Next, add media resources. The so-called media resources generally refer to websites or APPs. You can also understand them as Baidu's sites. Each media resource has a unique tracking ID, which is the ga we want to get.
But when adding media resources, we must pay attention, we need to click "View Advanced Options", turn on the "Create Universal Analytics Media Resources" switch, as to whether to check "Create Google Analytics 4 and Universal Analytics at the same time" or "Create Universal Analytics only" Analytics" is fine.
But only the ga created by Unviersal Analytics is the ga we need this time. The format it creates is the UA-00000000-0
. If it is created by Google Analytics 4, it starts with G.
One more word about Google Analytics 4. Google Analytics 4, referred to as GA4, is also a new version of GA. It will be released in October 2020. According to the introduction of official document
Google Analytics 4 (formerly "App + Web") is a new type of property that provides different reports than what you see in Universal Analytics properties. One of the advantages of a Google Analytics 4 property is that you can use it for your website, your app, or both. Universal Analytics properties only support websites.
After creation, we can see the generated ga:
Copy ga, we fill in the code of config.js
3.4 Verification
Note that Google Analytics is slightly different from Baidu Analytics. If we run it locally, we will not see any data reported. We can deploy the code to view it online:
collect
as shown in the figure, it means that the request was sent successfully.
3.5 Wait
According to official help document , we can know:
After adding the Analytics code to your website, Analytics will start sending data to your property within a few minutes (usually 10-15 minutes).
To confirm whether your property is receiving data, check the "Live" report. If you have your measurement code set up correctly, the "Current users" card will refresh every 15 seconds or so to show the latest user count.
Analytics takes 24-48 hours to process data for other reports.
4. Google or Baidu?
As for whether to use Google or Baidu, it varies from person to person. In China, Google will slow down the loading speed for some reasons. Of course, you can also use both.
series of articles
The blog building series is the only series of practical tutorials I have written so far, explaining how to use VuePress to build a blog and deploy it to GitHub, Gitee, personal servers and other platforms.
- An article that takes you to build a blog with VuePress + GitHub
- A tutorial to teach you how to synchronize GitHub and Gitee code
- won't use GitHub Actions yet? Check out this
- How does Gitee automatically deploy Pages? Or use GitHub Actions!
- A front-end Linux command
- A simple and sufficient Nginx Location configuration explanation
- An article that teaches you how to deploy your blog to your own server
- How to set the last updated time of VuePress blog optimization
WeChat: "mqyqingfeng", add me to the only readership of Xianyu.
If there are any mistakes or inaccuracies, please be sure to correct me, thank you very much. If you like or have inspiration, welcome to star, which is also an encouragement to the author.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。