Vue Analytics
Simple implementation of Google Analytics in Vue.js
This plugin will helps you in your common analytics tasks. Dispatching events, register some dimensions, metric and track views from Vue components.
Requirements
- Vue.js. >= 2.0.0
- Google Analytics account. To send data to
Optionnals dependencies
- Vue Router >= 2.x - In order to use auto-tracking of screens
Configuration
npm install vue-ua -S
or yarn add vue-ua
if you use Yarn package manager
Here is an example of configuration, compose with it on your own :
import VueAnalytics from 'vue-ua'
import VueRouter from 'vue-router'
const router = new VueRouter({routes, mode, linkActiveClass})
Vue.use(VueAnalytics, {
appName: '<app_name>',
appVersion: '<app_version>',
trackingId: '<your_tracking_id>',
debug: true,
vueRouter: router,
ignoredViews: ['homepage'],
trackPage: true|false,
createOptions: {
siteSpeedSampleRate: 10,
},
globalDimensions: [
{dimension: 1, value: 'MyDimensionValue'},
{dimension: 2, value: 'AnotherDimensionValue'}
],
globalMetrics: [
{metric: 1, value: 'MyMetricValue'},
{metric: 2, value: 'AnotherMetricValue'}
]
})
Documentation
Once the configuration is completed, you can access vue analytics instance in your components like that :
export default {
name: 'MyComponent',
data () {
return {
someData: false
}
},
methods: {
onClick: function() {
this.$ua.trackEvent('Banner', 'Click', 'I won money!')
this.$analytics.trackEvent('Banner', 'Click', 'I won money!')
}
},
mounted () {
this.$ua.trackView('MyScreenName')
}
}
You can also access the instance anywhere whenever you imported Vue
by using Vue.analytics
. It is especially useful when you are in a store module or
somewhere else than a component's scope.
Sync analytics with your router
Thanks to vue-router guards, you can automatically dispatch new screen views on router change !
To use this feature, you just need to inject the router instance on plugin initialization.
This feature will generate the view name according to a priority rule :
- If you defined a meta field for you route named
analytics
this will take the value of this field for the view name. - Otherwise, if the plugin don't have a value for the
meta.analytics
it will fallback to the internal route name.
Most of time the second case is enough, but sometimes you want to have more control on what is sent, this is where the first rule shine.
Example :
const myRoute = {
path: 'myRoute',
name: 'MyRouteName',
component: SomeComponent,
meta: {analytics: 'MyCustomValue'}
}
This will use MyCustomValue
as the view name.
API reference
trackEvent (category, action = null, label = null, value = null)
trackView (screenName, trackPage = false)
trackTiming (timingCategory, timingVar, timingValue, timingLabel = null)
injectGlobalDimension (dimensionNumber, value)
injectGlobalMetric (metricNumber, value)
trackException (description, isFatal = false)
changeSessionLanguage (code)