Google Analytics 可以很棒,如果你想知道你的应用程序是如何被使用的。 然而,通常在单页应用程序中,由于官方 Google Analytics 包的奇怪 API,直接获取适当的屏幕视图分析和连接事件更为困难。
安装
vue-ua 可以通过 Yarn 或 NPM 安装:
1# Yarn
2$ yarn add vue-ua -D
3
4# NPM
5$ npm install vue-ua --save-dev
设置
通过导入插件并启用所需配置参数在您的应用程序中初始化 vue-ua. 请注意, vue-ua 仅支持应用程序跟踪,而不是网络跟踪。
如果您正在使用 vue-router,您可以将其添加到 vue-ua 配置中,以便在 GA 中自动跟踪路线视图作为屏幕视图。
1[label src/main.js]
2import VueAnalytics from 'vue-ua'
3import VueRouter from 'vue-router'
4...
5// If you're using vue-router and want route integration, create your routes before enabling vue-ua.
6const router = new VueRouter({
7 routes
8})
9
10Vue.use(VueAnalytics, {
11 // [Required] The name of your app as specified in Google Analytics.
12 appName: '<app_name>',
13 // [Required] The version of your app.
14 appVersion: '<app_version>',
15 // [Required] Your Google Analytics tracking ID.
16 trackingId: '<your_tracking_id>',
17 // If you're using vue-router, pass the router instance here.
18 vueRouter: router,
19
20 // Global Dimensions and Metrics can optionally be specified.
21 globalDimensions: [
22 { dimension: 1, value: 'FirstDimension' },
23 { dimension: 2, value: 'SecondDimension' }
24 // Because websites are only 2D, obviously. WebGL? What's that?
25 ],
26
27 globalMetrics: [
28 { metric: 1, value: 'MyMetricValue' },
29 { metric: 2, value: 'AnotherMetricValue' }
30 ]
31})
数据发送
在您的组件中,您可以轻松跟踪事件,屏幕视图和例外,您也可以通过导入 Vue 并访问 Vue.analytics 在应用程序中的任何地方使用相同的全球方法。
** 追踪事件:**
1// Component Usage
2this.$ua.trackEvent(
3 eventCategory: string, eventAction: string, eventLabel: string, eventValue: number
4)
5
6// Global Usage
7Vue.analytics.trackEvent(
8 eventCategory: string, eventAction: string, eventLabel: string, eventValue: number
9)
** 监控屏幕视图:**
1// Component Usage
2this.$ua.trackView(routeName: string)
3
4// Global Usage
5Vue.analytics.trackView(routeName: string)
** 追踪例外:**
1// Component Usage
2this.$ua.trackException(description: string, isFatal: boolean)
3
4// Global Usage
5Vue.analytics.trackException(description: string, isFatal: boolean)
改變語言:**
1// languageCode is any valid IETF language tag.
2
3// Component Usage
4this.$ua.changeSessionLanguage(languageCode: string)
5
6// Global Usage
7Vue.analytics.changeSessionLanguage(languageCode: string)
您现在拥有所有您需要的工具来收集用户在 Vue.js SPA 中所做的一切数据。