在 plugins
文件夹下新建文件 ga.js
,填入以下内容:
/*
** 只在生产模式的客户端中使用
*/
if (process.client && process.env.NODE_ENV === 'production') {
/*
** Google 统计分析脚本
*/
;(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r
;(i[r] =
i[r] ||
function() {
;(i[r].q = i[r].q || []).push(arguments)
}),
(i[r].l = 1 * new Date())
;(a = s.createElement(o)), (m = s.getElementsByTagName(o)[0])
a.async = 1
a.src = g
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga')
/*
** 当前页的访问统计
** 替换为你自己的UA
*/
ga('create', 'UA-xxxxxxxxx-x', 'auto')
}
export default ({ app: { router }, store }) => {
/*
** 每次路由变更时进行pv统计
*/
router.afterEach((to, from) => {
/*
** 告诉 GA 增加一个 PV
*/
ga('set', 'page', to.fullPath)
ga('send', 'pageview')
})
}
修改 nuxt.config.js
文件内容
export default {
...
plugins: [{ src: '@/plugins/ga.js', ssr: false }],
...
}
登录你的Google Analytics,即可查看分析数据