Vue项目中加入百度统计

2,110 阅读1分钟

Vue框架作为优秀的前端框架,已经越来越受到开发者的重视和喜爱。本文就如何在Vue项目中添加百度统计代码进行详细的阐述。

一、在百度统计后台加入网站域名

1、打开百度统计,并登陆(如为注册请先注册)

[tongji.baidu.com/]:

2、在管理-新增网站,添加自己网站的域名

要添加的域名如:m.yourdomain.com/yourproject/#/index

二、修改Vue项目中的index.html文件

1、在中head标签中添加如下代码:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<link href="./static/favicon.ico" rel="shortcut icon" type="image/x-icon">
<title></title>
<script>
    var _hmt = _hmt || [];
</script>
</head>
2、在body标签中加入:
<script>
    (function() {
        var hm = document.createElement('script');
        hm.src = 'https://hm.baidu.com/hm.js?23c7003auj3e6346c36bd4c7etg324e';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

三、在main.js中,路由的钩子函数中加入:

router.beforeEach(function (to, from, next) {
    if (to.path) {
    _hmt.push(['_trackPageview', to.fullPath])
    }
    next();
    store.commit('updateLoadingStatus', {isLoading: true})
    next()
})

四、在Vue文件中的使用

toLink(url){
	_hmt.push(['_trackPageview',  '/m.yourdomain.com/?userid=123456'])
}