How to set up analytics in Vue
Contents
Product analytics enable you to gather and analyze data about how users interact with your Vue.js app. To show you how to set up analytics, in this tutorial we create a basic Vue app, add PostHog, and use it to capture pageviews and custom events.
Creating a Vue app
To demonstrate the basics of PostHog analytics, we'll create a simple Vue 3 app with two pages and a link to navigate between them.
First, ensure Node.js is installed (version 18.0 or newer). Then install @vue/cli and create a new Vue app:
Make sure to select [Vue 3] babel, eslint as the Vue version.
Adding pages
Next, create two new files HomePage.vue and AboutPage.vue in src/components.
In HomePage.vue, add the following the code:
In AboutPage.vue, add the following the code:
Next we set up the routing. First install Vue Router in your project:
In your src directory, create a new folder router and then a new file index.js:
In router/index.js, import the components and define the routes:
Then, update your App.vue to use the router-view. Replace the contents of this file with:
Finally, set up main.js to use the router:
The basic setup is now complete. Run npm run serve to see your app.

Adding PostHog
This tutorial shows how to integrate PostHog with
Vue 3. If you're usingVue 2, see our Vue docs for how to integrate PostHog.
With our app set up, it’s time to install and set up PostHog. If you don't have a PostHog instance, you can sign up for free.
First, install posthog-js:
Create a new plugin by creating a new folder in your base directory called plugins and then a new file posthog.js:
In posthog.js, initialize PostHog with your project API key and host. You can find these in your project settings.
Finally, activate your plugin in main.js:
Once you’ve done this, reload your app and click the buttons a few times. You should see events and pageviews appearing in the activity explorer.


Capturing custom events
Beyond pageviews, there might be more events you want to capture. To do this, you can capture custom events with PostHog.
To showcase this, update the code in HomePage.vue with a button and captureCustomEvent method that uses PostHog to capture a home_button_clicked event:
Now when you click the button, PostHog captures the custom home_button_clicked event. Notice that we also added a property user_name to the event. This is helpful for filtering events in PostHog.
Further reading
Subscribe to our newsletter
Product for Engineers
Read by 100,000+ founders and builders
We'll share your email with Substack