Static
If you are using Nuxt.js to generate full static pages
Edit layouts/default.vue
<script>export default { head() { let productionScripts = [] if (process.env.NODE_ENV === 'production') { productionScripts = [ { hid: 'analytics', src: 'https://www.googletagmanager.com/gtag/js?id=UA-3625XXXX-1', defer: true }, { hid: 'analytics-script', innerHTML: "window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-3625XXXX-1');", type: 'text/javascript' } ] } return { title: "Test Analytics", script: [ ].concat(productionScripts), // __dangerouslyDisableSanitizers: ['script'] __dangerouslyDisableSanitizersByTagID: { 'analytics-script': ['innerHTML'] } } }}</script>
Dynamic
If you are using SSR or SPA, which vue-router is used to change pages dynamically, you can use @nuxtjs/google-analytics.
Install
npm install --save-dev @nuxtjs/google-analytics
Edit nuxt.config.js
export default {
buildModules: [
'@nuxtjs/google-analytics'
],
googleAnalytics: {
id: 'UA-3625XXXX-1'
}
}
NOTE: Analytics is disabled in development mode
NOTE: You will notice you will not find google analytics url in the generated html (I assume it is done via JavaScript). You can enable debug mode to check if it is working.
export default {
googleAnalytics: {
id: 'UA-3625XXXX-1',
debug: {
enabled: true,
// sendHitTask: true
}
}
}
NOTE: @nuxtjs/google-analytics
utilize (vue-analytics)https://github.com/MatteoGabriele/vue-analytics, where the size is not tiny.
NOTE: You can also do it manually without using plugins.
Firebase Analytics
If you are using Firebase, you can use Firebase Analytics instead of Google Analytics.