基于VUE安装GA统计
AI摘要:文章介绍了在Vue单页面应用中集成Google Analytics的方法,包括使用vue-ga插件安装配置,以及基于vue-router的多种实现方案,提供了有路由和无路由情况下的代码示例和替代方法。
现在网站流行单页面应用,普通的GA代码引入可能没办法正确的执行统计代码了,这里先给出一个基于VUE开发的一个GA插件vue-ga。
安装:
npm install vue-ga如果项目使用vue-router
// ./router/index.js
import VueRouter from 'vue-router'
import ga from 'vue-ga'
Vue.use(VueRouter)
const router = new VueRouter()
ga(router, 'UA-XXXXX-Y')
export default router把UA-XXXXX-Y替换成自己的ID。
如果项目没有使用vue-router在每次路由改变的时候,使用collect函数,例如:
ga(collect => {
// when hash changes
window.onhashchange = () => {
collect(location.pathname + location.hash)
}
}, 'UA-XXXXX-Y')补充:
不用vue-ga,但是使用vue-router的通用方法方法:
先再index.html引入GA代码;
然后在控制路由的地方打点使用导航守卫:
router.afterEach((to, from) => {
console.log('from', from.fullPath)
console.log('to', to.fullPath)
console.log('location.href' + location.host + to.fullPath) // instead of location.href
if (window.ga) {
window.ga('send', 'pageview', to.fullPath);
}
});使用新的gtag代码:
// 使用导航守卫发送统计
router.afterEach((to, from) => {
if (window.gtag) {
window.gtag('config', 'UA-84926428-5', {
'page_path': to.fullPath
});
}
});另外,给出一篇谷歌官方的文档单页应用跟踪

router_interceptor.js 文件怎么拦截第一个页面,every 和match都拦截不到
什么?