Vue.js

Last updated:

|Edit this page

PostHog makes it easy to get data about usage of your Vue.js app. Integrating PostHog into your app enables analytics about user behavior, custom events capture, session replays, feature flags, and more.

This guide walks you through integrating PostHog into your app for both Vue.js major versions 2 and 3. We'll use the JavaScript Web SDK for this.

For integrating PostHog into a Nuxt.js app, see our Nuxt guide.

Prerequisites

To follow this guide along, you need:

  1. A PostHog account (either Cloud or self-hosted)
  2. A running Vue.js app

Setting up PostHog

Start by installing posthog-js using your package manager:

Terminal
yarn add posthog-js
# or
npm install --save posthog-js

Next, depending on your Vue version, we recommend initializing PostHog using the composition API or as a plugin.

We use the Composition API as it provides better accessibility, maintainability, and type safety.

Start by creating a composables folder as well as a usePosthog.js file to that folder. In usePosthog.js, initialize PostHog as a composable:

JavaScript
// src/composables/usePostHog.ts
import posthog from 'posthog-js'
export function usePostHog() {
posthog.init('<ph_project_api_key>', {
api_host: 'https://us.i.posthog.com'
})
return {
posthog
}
}

Next, in router/index.js, import the usePostHog composable and call it.

JavaScript
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { usePostHog } from '@/composables/usePostHog'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue'),
},
],
})
const { posthog } = usePostHog()
export default router

Once done, PostHog will begin autocapturing events (if enabled) and is ready to use throughout your app.

Capturing pageviews

PostHog captures pageviews on page load, and since Vue creates a single-page app, this only happens once. This means if we want to capture every route change, we must write code to capture pageviews that integrates with the router.

First, disable autocaptured pageviews by setting capture_pageview to false in the PostHog initialization config:

JavaScript
// src/composables/usePostHog.ts
import posthog from 'posthog-js'
export function usePostHog() {
posthog.init('<ph_project_api_key>', {
api_host: 'https://us.i.posthog.com',
capture_pageview: false
})
return {
posthog
}
}

Next, in router/index.js, set up PostHog to capture pageviews in the router.afterEach function.

JavaScript
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { usePostHog } from '@/composables/usePostHog'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue'),
},
],
})
const { posthog } = usePostHog()
router.afterEach((to) => {
posthog.capture('$pageview')
})
export default router

Capturing pageleaves

Pageleaves are similar to pageviews, they need to be manually captured.

To capture pageleaves, we can simply use the beforeEach hook in the router.

JavaScript
// src/router/index.js
//... rest of your code
const { posthog } = usePostHog()
router.beforeEach((to, from) => {
if (from.path !== to.path) {
posthog.capture('$pageleave')
}
})
//... rest of your code

Capturing custom events, using feature flags, and more

Once you have PostHog initialized, there is a lot more you can do with it beyond autocapture, pageviews, and pageleaves. You can find the full details in our JavaScript SDK docs, but we'll cover a few examples here.

To capture custom events, evaluate feature flags, and use any of the other PostHog features, you can use the posthog object returned from the usePostHog composable like this:

JavaScript
// src/App.vue
<script setup>
import { RouterView } from 'vue-router'
import { usePostHog } from './composables/usePostHog'
const { posthog } = usePostHog()
const handleClick = () => {
posthog.capture('button_clicked', { location: 'homepage' })
}
const isFeatureEnabled = posthog.isFeatureEnabled('test-flag')
</script>
<template>
<div>
<button @click="handleClick">Click me!</button>
<p>Is feature flag enabled? {{ isFeatureEnabled ? 'Yes' : 'No' }}</p>
</div>
<RouterView />
</template>

Other setup options

With Vue 3, developers can use provide() and inject() to pipe global values into any component without prop drilling. And if you don't know what prop drilling is, good for you.

While this method is more declarative, as you need to inject PostHog into every component, it avoids “polluting” globals (like the plugins can do). Some engineers prefer this approach, while others include PostHog in globals since it doesn't need to be reactive and will be called throughout your application.

Step 1: Initialize Vue

Prior to mounting the app, you must:

  1. Import PostHog
  2. Initialize it
  3. Provide it to your app.

This must be done before you mount your app. If you provide PostHog after mounting it, PostHog will not be predictably available.

JavaScript
//app.js
import posthog from "posthog-js";
const app = createApp(App);
posthog.init("<ph_project_api_key>", {
api_host: "https://us.i.posthog.com",
person_profiles: 'identified_only',
});
app.provide("posthog", posthog);

Step 2: Inject into any Vue file

JavaScript
//component.vue
export default {
data() {
return {
greeting: "How are you!",
};
},
inject: ["posthog"], //grab the injection from app-wide provider
created() {
console.log("Created", this.posthog); //posthog accessible!
},
};

Next steps

For any technical questions for how to integrate specific PostHog features into Vue (such as analytics, feature flags, A/B testing, or surveys), have a look at our JavaScript Web SDK docs.

Alternatively, the following tutorials can help you get started:

Questions?

Was this page useful?

Next article

Webflow

PostHog makes it easy to get data about traffic and usage of your Webflow app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more. This guide walks you through integrating PostHog into your Webflow app using the JavaScript Web SDK . Installation Next steps For any technical questions for how to integrate specific PostHog features into Webflow (such as analytics, feature flags, A/B testing, surveys, etc…

Read next article