vue单页面应用加入百度统计

版权声明:本文为CSDN博主「钟文辉」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39753974/article/details/80322643

在单页面中,要是只加在head中的话那是没用的,因为只能运行一次。

在百度中复制代码

将代码放在index.html的head中

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

  

在路由的beforeEach函数中使用

// router.js
let router= new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
        path: '*',
        name: 'error_404',
        component: error_404
    }
  ]
});

router.beforeEach((to, from, next) => {
    if (to.path) {
        _hmt.push(['_trackPageview', '/#' + to.fullPath]);
    }
    next();
}

  

检测是否安装成功

打开控制台查看网络请求 
每次路由变化就会发出一个叫hm.gif的请求

两个小时候再进网页就会有统计数据

原文地址:https://www.cnblogs.com/chenguangliang/p/11412088.html