Home  >  Article  >  Web Front-end  >  How to implement Baidu statistics using vue

How to implement Baidu statistics using vue

亚连
亚连Original
2018-06-08 15:52:493362browse

This article mainly introduces the solution of adding Baidu statistics code to vue single-page application. Friends who need it can refer to it

After applying for Baidu statistics, you will get a piece of JS code that needs to be inserted into each web page. In the Vue.js project, the first thing that comes to mind may be to insert the statistical code into the index.html entry file, so that it can be inserted globally and available on every page; this involves a problem, Vue.js The project is a single-page application. Every time a user browses the website, the page will not be refreshed when accessing the internal page, which means that the Baidu statistics code will not be triggered; so the final effect seen in the Baidu statistics background is that only the web page is counted. The traffic of the entrance cannot be counted, but the traffic of the internal pages cannot be counted.

Solution

Call the afterEach method of vue-router in the main.js file and add the statistical code to this method, like this Every time the router changes, the statistical code will be executed, thus achieving the purpose. The code is as follows:

router.afterEach( ( to, from, next ) => {
 setTimeout(()=>{
   var _hmt = _hmt || [];
   (function() {
    //每次执行前,先移除上次插入的代码
    document.getElementById('baidu_tj') && document.getElementById('baidu_tj').remove();
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?xxxx";
    hm.id = "baidu_tj"
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
   })();
 },0);
} );

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement the double-color ball function in JS

How to implement the snow animation effect in jQuery

How to achieve the pull-down refresh and pull-up loading effect of the list in the WeChat applet?

The above is the detailed content of How to implement Baidu statistics using vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn