Tracking page views and clicks in your Vue project

Understanding your user's behavior as they navigate through and interact with your website is essential.

While SPA frameworks are traditionally tricky to track, Lyticus is an entry-level web analytics tool that was designed to play well with modern frameworks from the get-go.

In this short tutorial you'll learn how to track page views and clicks in your Vue project.

Prerequisites

If you don't have a Lyticus account, you can sign up for free here, free accounts can create up to 3 websites and track up to 10K page views per month.

This tutorial also assumes that your main.js file contains at least the following:

import Vue from 'vue' import App from './App.vue' import router from './router' new Vue({ router, render : h => h(App) }).$mount( '#app' )

Installing the tracker

The Lyticus tracker is a tiny JavaScript library that enables you to tracks various metrics such as page views and clicks.

It is flexible and easily configurable: you control which events to track and when to track them.

To install the tracker via NPM:

npm install lyticus

You can learn more about the tracker here.

Creating the tracker instance

Before you can start sending events, you need to create a lyticus instance.

It is through this lyticus instance that you will initiate all tracking.

Copy your unique website id (you can sign up for a free account to obtain one) and adapt your main.js file:

import Vue from 'vue' import App from './App.vue' import router from './router' import Lyticus from 'lyticus' const lyticus = new Lyticus( 'your-website-id' , { development : process.env.NODE_ENV === 'development' }) new Vue({ router, render : h => h(App) }).$mount( '#app' )

Tracking the navigator and page views

The trackNavigator method tracks the navigator's details (screen width, language, operating system, browser).

The startHistoryMode method overrides the pushState method of the browser to automatically track page views in your SPA.

Adapt your main.js file:

import Vue from 'vue' import App from './App.vue' import router from './router' import Lyticus from 'lyticus' const lyticus = new Lyticus( 'your-website-id' , { development : process.env.NODE_ENV === 'development' }) lyticus.trackNavigator() lyticus.startHistoryMode() new Vue({ router, render : h => h(App) }).$mount( '#app' )

Tracking click events inside your components

Adding $lyticus to the Vue prototype enables you to call Lyticus methods from within your components..

Adapt your main.js file:

const lyticus = new Lyticus( 'you-website-id' ) Vue.prototype.$lyticus = lyticus

You can now start tracking clicks inside any component:

< template > < button @ click = "onRedButtonClick" > Hello </ button > </ template > < script > export default { methods : { onRedButtonClick() { this .$lyticus.trackClick( 'red-button' ) } } } </ script >

Conclusion

In this short tutorial you learned how to track page views and clicks in your Vue project.

Links