Blog>
Snippets

Vue.js Analytics Plugin

Create a plugin that integrates with Google Analytics or a similar service to track page views and custom events in a Vue.js application.
import Vue from 'vue';
import VueAnalytics from 'vue-analytics';

export function createAnalyticsPlugin({ id, router }) {
  // Ensure the Google Analytics ID is provided
  if (!id) throw new Error('Google Analytics id is required');

  // Initialize VueAnalytics only if running in the browser
  if (typeof window !== 'undefined') {
    Vue.use(VueAnalytics, {
      id,
      router,
      autoTracking: {
        pageviewOnLoad: false
      }
    });
  }
}
This is a JavaScript module that exports a function to create the Google Analytics plugin for Vue.js. The `createAnalyticsPlugin` function initializes VueAnalytics with a provided Google Analytics ID and Vue router instance, if available.
<template>
  <div>
    <router-view />
  </div>
</template>

<script>
import { createAnalyticsPlugin } from './analytics-plugin';

export default {
  name: 'App',
  created() {
    // Initialize the analytics plugin when the app is created
    createAnalyticsPlugin({
      id: 'UA-XXXXXXXXX-X', // Your Google Analytics tracking ID
      router: this.$router // Pass the Vue router for page tracking
    });
  }
};
</script>
This snippet demonstrates the usage of the analytics plugin within a Vue.js component, typically the main App component. It imports the `createAnalyticsPlugin` function and initializes it in the `created` lifecycle hook using the Google Analytics tracking ID and Vue router.
.ga-event-button {
  cursor: pointer;
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
}

.ga-event-button:hover {
  background-color: #45a049;
}
This is the CSS for a button that will be used to trigger custom Google Analytics events. It includes basic styling and a hover effect.
<template>
  <button class="ga-event-button" @click="sendCustomEvent">
    Click to Track Event
  </button>
</template>

<script>
export default {
  methods: {
    sendCustomEvent() {
      // Sending a custom event to Google Analytics
      this.$ga.event({
        eventCategory: 'Category',
        eventAction: 'Action',
        eventLabel: 'Label',
        eventValue: 1
      });
    }
  }
};
</script>
This snippet shows a Vue.js template with a button that, when clicked, will call the `sendCustomEvent` method. The method triggers a custom event in Google Analytics using the VueAnalytics `$ga.event` method with specified event properties.