vue项目中使用百度统计

时间:2023-03-09 20:14:31
vue项目中使用百度统计

统计有多少人访问了自己的网站(wap端pc web端都适用),或者更细的统计网站每个页面的访问量,可以使用百度统计

百度统计传送门

按提示注册登录即可

登录后-->管理-->新增网站,配置好后会出现如下的 自有网站列表

vue项目中使用百度统计

在要统计的网站 右侧,点击“获取代码”

vue项目中使用百度统计

拷贝要统计网站的代码

vue项目中使用百度统计

统计vue项目中的每个页面的访问量

1.在main.js中 贴入 拷贝的代码 并稍作修改,使用window全局变量,如下:

var _hmt = _hmt || [];
window._hmt = _hmt; // 修改为window 全局变量
(function () {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?"+ 百度站点id;
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();

不使用window全局变量:_hmt会找不到然后报错,这是因为在一个js文件里声明的变量在另一个js文件里是找不到的,所以需要把_hmt挂载到window对象下,这样_hmt成为了全局变量,就可以在任何地方访问了

2.在路由创建实例后,调用beforeEach方法,保证每个路由跳转时都将其跳转的路由推给百度。

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Main from '../pages/Main.vue' Vue.use(Router)
const routes = [
{
path: '/hellowold',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/main',
name: 'Main',
component: Main
}
] // export default new Router({
// // mode: 'history',
// routes: routes
// }) const router = new Router({
routes: routes
}) router.beforeEach((to, from, next) => {
if (window._hmt) {
if (to.path) {
window._hmt.push(['_trackPageview', '/#' + to.fullPath])
}
}
next()
}) export default router

https://www.jianshu.com/p/febd38110645

单页面vue引入百度统计 https://www.cnblogs.com/zengfp/p/9778119.html