Vue.js
Track user interactions and page views in your Vue.js applications seamlessly with Usermaven. This guide provides instructions for integrating with both Vue 3 and Vue 2.
Core features:
Automatic and manual tracking of page views.
Custom event tracking with detailed properties.
User identification to associate activity with specific users.
Support for various configurations like cross-domain tracking and URL randomization.
Vue 3 integration
For Vue 3 applications, use the dedicated @usermaven/vue package.
1. Installation
# Using npm
npm install @usermaven/vue
# Using yarn
yarn add @usermaven/vue
2. Initialization
Initialize the Usermaven plugin in your application's main entry file (usually main.js or main.ts).
// main.js or main.ts
const app = createApp(App);
app.use(UsermavenPlugin, {
// Required
key: 'YOUR_USERMAVEN_API_KEY', // Replace with your actual API key
trackingHost: 'https://events.usermaven.com', // Or your custom proxy/CNAME URL e.g., 'https://stats.yourdomain.com' if configured already.
// Common Optional Settings
autoPageview: true, // Default: false. Automatically tracks page views on route changes.
autocapture: true, // Default: false. Enables automatic capturing of predefined user interactions.
randomizeUrl: true, // Default: false. Set to true to anonymize URL parameters.
// namespace: 'my-app', // Optional: For isolating multiple Usermaven instances.
// For cross-domain tracking
// crossDomainLinking: true, // Default: false. Set to true to enable. Not required for subdomains
// domains: 'primary.com,secondary.org', // Comma-separated list of domains, not required for subdomains
});
app.mount('#app');
Key Configuration Notes:
key: Your unique Usermaven Workspace API Key.trackingHost: If you've set up Pixel white-labeling or proxyor a similar proxy, use your custom domain here.autoPageview: Iftrue, the SDK will automatically track page views when your Vue Router navigates.autocapture: Iftrue, the SDK will automatically track user interactions like button clicks, and more.
3. Tracking page views
You **must** use the `usePageView` composable to enable automatic page view tracking with Vue Router. Add it to a central component like `App.vue` or your main layout:
```vue
<script setup>
// This enables page view tracking for route changes.
const _ = usePageView();
</script>
```
4. Identifying users & identity resolution
When a user first visits your site, Usermaven automatically assigns them an anonymous_id to track their pre-login activity. When the user logs in, signs up, or their identity otherwise becomes known, you should call the usermaven.id() method. This call serves two main purposes:
It associates the user with their known
id(e.g., your database user ID) and other attributes.It stitches their previously anonymous activity to their now identified profile, providing a complete user journey.
<script setup>
const usermaven = useUsermaven();
function identifyUserOnLogin(userData) {
usermaven.id({
// Required
id: userData.id, // Your system's unique ID for the user (e.g., 'USER_123')
email: userData.email, // User's email address
created_at: userData.signUpDate, // ISO 8601 DateTime string (e.g., '2023-05-15T10:30:00Z') or a Date object
// Recommended
first_name: userData.firstName,
last_name: userData.lastName,
// Optional custom attributes
// custom: {
// plan_name: 'premium',
// trial_ends_at: '2023-06-15T10:30:00Z'
// },
// Optional company attributes (for B2B SaaS)
// company: {
// Required
// id: userData.companyId, // Your system's unique ID for the company
// name: userData.companyName,
// created_at: userData.companySignUpDate, // ISO 8601 DateTime string or Date object
//
// Optional custom attributes
// custom: {
// industry: 'Software',
// employees: 50,
// role: 'Admin'
// }
// }
});
}
</script>
Note on created_at fields: Provide dates as ISO 8601 formatted strings (e.g., YYYY-MM-DDTHH:mm:ssZ) or JavaScript Date objects.
5. Tracking custom events
Use the track method from the useUsermaven composable.
<script setup>
const usermaven = useUsermaven();
function trackProductAddedToCart(product) {
usermaven.track('product_added_to_cart', {
productId: product.id,
productName: product.name,
category: product.category,
price: product.price,
currency: 'USD',
});
}
</script>
<template>
<!-- Example usage -->
<!-- <button @click="trackProductAddedToCart(someProduct)">Add to Cart</button> -->
</template>
Vue 2 Integration
For Vue 2 applications, we recommend using the @usermaven/sdk-js (our general JavaScript SDK), configured as a Vue plugin.
1. Installation
# Using npm
npm install @usermaven/sdk-js
# Using yarn
yarn add @usermaven/sdk-js
2. Initialization (as a Vue Plugin)
Create a new plugin file (e.g., src/plugins/usermaven.js):
// src/plugins/usermaven.js
// Initialize the Usermaven client
// Required
key: 'YOUR_USERMAVEN_API_KEY', // Replace with your actual API key
trackingHost: 'https://events.usermaven.com', // Or your custom proxy/CNAME URL e.g., 'https://stats.yourdomain.com' if configured already.
// Common Optional Settings
autoPageview: true, // Default: false. Automatically tracks page views on route changes.
autocapture: true, // Default: false. Enables automatic capturing of predefined user interactions.
randomizeUrl: true, // Default: false. Set to true to anonymize URL parameters.
// namespace: 'my-app', // Optional: For isolating multiple Usermaven instances.
// For cross-domain tracking
// crossDomainLinking: true, // Default: false. Set to true to enable. Not required for subdomains
// domains: 'primary.com,secondary.org', // Comma-separated list of domains, not required for subdomains
});
// Make Usermaven available on the Vue prototype (e.g., this.$usermaven)
Vue.prototype.$usermaven = usermaven;
// You can also export the client for use in non-component files like router.js
export default usermaven; // Or export { usermaven };
Key Configuration Notes:
key: Your unique Usermaven Workspace API Key.trackingHost: If you've set up Pixel white-labeling or proxyor a similar proxy, use your custom domain here.autoPageview: Iftrue, the SDK will automatically track page views when your Vue Router navigates.autocapture: Iftrue, the SDK will automatically track user interactions like button clicks, and more.
Now, register this plugin in your main application file (e.g., src/main.js):
// src/main.js
}).$mount('#app');
3. Tracking Page Views (with Vue Router)
While @usermaven/sdk-js has an autoPageview option, for Vue 2 SPAs, explicit tracking with Vue Router's navigation guards provides clear control.
Modify your router setup (e.g., src/router/index.js):
// src/router/index.js
// Import the Usermaven client instance directly from your plugin file
Vue.use(VueRouter);
const routes = [
// ... your routes
];
const router = new VueRouter({
mode: 'history', // Or 'hash'
base: process.env.BASE_URL,
routes,
});
router.afterEach((to, from) => {
// Ensure Usermaven client is available
if (usermaven && typeof usermaven.track === 'function') {
usermaven.track('pageview', {
path: to.fullPath, // Or to.path
referrer: from.fullPath, // Or from.path
title: document.title, // Capture after title has been updated by route meta or navigation guards
});
}
});
export default router;
If you set autoPageview: true in the Vue 2 usermavenClient config, it might handle some scenarios, but the router.afterEach hook is generally more reliable for SPA page view tracking in Vue 2. Test thoroughly if using autoPageview: true.
4. Identifying Users
Access Usermaven methods via this.$usermaven in your components.
// Example in a Vue component
<script>
export default {
methods: {
identifyUserOnLogin(userData) {
this.$usermaven.id({
// Required
id: userData.id, // Your system's unique ID (e.g., 'USER_123')
email: userData.email,
created_at: userData.signUpDate, // ISO 8601 DateTime string or Date object
// Recommended
first_name: userData.firstName,
last_name: userData.lastName,
// Optional company attributes (for B2B SaaS)
// company: {
// Required
// id: userData.companyId, // Your system's unique ID for the company
// name: userData.companyName,
// created_at: userData.companySignUpDate, // ISO 8601 DateTime string or Date object
// Optional custom attributes
// custom: {
// industry: 'Software',
// employees: 50,
// role: 'Admin'
// }
// }
});
},
},
};
</script>
5. Tracking Custom Events
// Example in a Vue component
<script>
export default {
methods: {
trackVideoPlay(videoDetails) {
this.$usermaven.track('video_played', {
videoId: videoDetails.id,
videoTitle: videoDetails.title,
duration: videoDetails.duration,
});
},
},
};
</script>
Key Configuration Options
This table summarizes common configuration options for both UsermavenPlugin (Vue 3) and usermavenClient(Vue 2/JS).
Option | Type | Default | Description |
|---|---|---|---|
| String | — | Required. Your Usermaven Workspace API Key. |
| String | — | Required. Usermaven tracking server URL (e.g., |
| Boolean |
| If |
| Boolean |
| If |
| Boolean |
| If |
| String |
| A custom namespace if you need to run multiple Usermaven instances on the same page. |
| Boolean |
| If |
| String |
| Comma-separated list of domains for cross-domain linking (e.g., |
For a complete list of all SDK methods and advanced configuration options, please refer to the official Usermaven SDK Reference Guide.
Was this article helpful?