npm package: @plainapps/analytics-vue
Description: Vue composables and plugin for Plain Web Analytics - privacy-focused, cookie-free analytics
Author: Plain Web Analytics
Latest version: 1.0.2

# @plainapps/analytics-vue

Vue composables and plugin for [Plain Web Analytics](https://plainwebanalytics.com) - privacy-focused, cookie-free web analytics.

## Features

- 🎯 **Vue 3 Composition API** - Native Vue 3 composables
- 🔌 **Plugin support** - Global installation with Vue plugin
- 📊 **Automatic pageviews** - Track pageviews automatically or manually
- 🎯 **Event tracking** - Track custom events and goal conversions
- 🛤️ **Vue Router integration** - Built-in support for route change tracking
- 🌐 **Nuxt 3 compatible** - Works seamlessly with Nuxt 3
- ⚡ **Lightweight** - Tree-shakeable, zero dependencies beyond core
- 📝 **TypeScript** - Full TypeScript support with type definitions

## Installation

```bash
npm install @plainapps/analytics-vue
# or
yarn add @plainapps/analytics-vue
# or
pnpm add @plainapps/analytics-vue
```

## Quick Start

### Option 1: Plugin (Recommended)

Install the plugin in your Vue app:

```ts
// main.ts
import { createApp } from 'vue';
import { createPlainAnalytics } from '@plainapps/analytics-vue';
import App from './App.vue';

const app = createApp(App);

app.use(createPlainAnalytics({
  siteId: 'pwa_site_abc123',  // Your site key
}));

app.mount('#app');
```

Then use composables in your components:

```vue
<script setup lang="ts">
import { usePlainAnalytics, useTrackEvent } from '@plainapps/analytics-vue';

// Access full context
const { trackEvent, trackGoal, isInitialized } = usePlainAnalytics();

// Or use specialized composables
const { track, isReady } = useTrackEvent();

function handleSignup() {
  track('signup_click', { source: 'homepage' });
}
</script>

<template>
  <button @click="handleSignup" :disabled="!isReady">
    Sign Up
  </button>
</template>
```

### Option 2: Standalone Composable

Use without the plugin:

```vue
<script setup lang="ts">
import { usePlainAnalytics } from '@plainapps/analytics-vue';

const { trackEvent, isInitialized } = usePlainAnalytics({
  siteId: 'pwa_site_abc123',
});

function handleClick() {
  trackEvent('button_click', { button: 'cta' });
}
</script>
```

## Vue Router Integration

Track pageviews on route changes:

```vue
<!-- App.vue or a layout component -->
<script setup lang="ts">
import { usePageViews } from '@plainapps/analytics-vue';
import { useRoute } from 'vue-router';

const route = useRoute();

// Track pageviews when route changes
usePageViews(() => route.fullPath);
</script>
```

## Nuxt 3 Integration

Create a client-side plugin:

```ts
// plugins/analytics.client.ts
import { createPlainAnalytics } from '@plainapps/analytics-vue';

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(createPlainAnalytics({
    siteId: 'pwa_site_abc123',
  }));
});
```

Track route changes in your app:

```vue
<!-- app.vue or layouts/default.vue -->
<script setup lang="ts">
import { usePageViews } from '@plainapps/analytics-vue';

const route = useRoute();
usePageViews(() => route.fullPath);
</script>
```

## API Reference

### Plugin

#### `createPlainAnalytics(options)`

Creates a Vue plugin for Plain Web Analytics.

```ts
interface PlainAnalyticsPluginOptions {
  siteId: string;           // Required: Your site key
  apiEndpoint?: string;     // Custom API endpoint
  autoPageview?: boolean;   // Auto-track initial pageview (default: true)
  hashMode?: boolean;       // Track hash changes (default: false)
  debug?: boolean;          // Enable debug logging (default: false)
}
```

### Composables

#### `usePlainAnalytics()`

Access the analytics context from the plugin.

```ts
const {
  isInitialized,    // Ref<boolean> - Whether analytics is ready
  isEnabled,        // Ref<boolean> - Whether tracking is enabled
  config,           // Ref<AnalyticsConfig | null> - Current configuration
  trackPageview,    // (url?: string) => void - Track a pageview
  trackEvent,       // (name: string, properties?: EventProperties) => void
  trackGoal,        // (goalId: string, options?: GoalOptions) => void
  setEnabled,       // (enabled: boolean) => void - Enable/disable tracking
} = usePlainAnalytics();
```

#### `usePlainAnalytics(options)`

Create a standalone analytics instance (no plugin required).

```ts
const { trackEvent, isInitialized } = usePlainAnalytics({
  siteId: 'pwa_site_abc123',
});
```

#### `usePageViews(source, options?)`

Track pageviews when a reactive source changes.

```ts
const route = useRoute();
usePageViews(() => route.fullPath, {
  trackOnMount: false,  // Track initial pageview (default: false)
});
```

#### `useTrackEvent()`

Get a track function for custom events.

```ts
const { track, isReady } = useTrackEvent();

track('button_click', { button: 'signup' });
```

#### `useTrackOnMount(eventName, properties?)`

Track an event when the component mounts.

```ts
// Track product views
useTrackOnMount('product_view', { product_id: 'abc123' });
```

#### `useTrackGoal()`

Get a function for tracking goal conversions.

```ts
const trackGoal = useTrackGoal();

// Track a purchase with revenue (in cents)
trackGoal('purchase', { revenue: 9900 });
```

## Examples

### Track a Button Click

```vue
<script setup lang="ts">
import { useTrackEvent } from '@plainapps/analytics-vue';

const { track } = useTrackEvent();

function handleAddToCart(productId: string) {
  track('add_to_cart', { product_id: productId });
}
</script>

<template>
  <button @click="handleAddToCart('prod-123')">
    Add to Cart
  </button>
</template>
```

### Track a Form Submission

```vue
<script setup lang="ts">
import { usePlainAnalytics } from '@plainapps/analytics-vue';

const { trackEvent, trackGoal } = usePlainAnalytics();

async function handleSubmit() {
  const success = await submitForm();
  
  if (success) {
    trackEvent('form_submit', { form: 'contact' });
    trackGoal('lead_capture');
  }
}
</script>
```

### Track E-commerce Purchase

```vue
<script setup lang="ts">
import { useTrackGoal } from '@plainapps/analytics-vue';

const trackGoal = useTrackGoal();

async function handleCheckout(cart: Cart) {
  const order = await processPayment(cart);
  
  // Track purchase with revenue in cents
  trackGoal('purchase', {
    revenue: order.total * 100,
    properties: {
      order_id: order.id,
      items: cart.items.length,
    },
  });
}
</script>
```

### Conditional Tracking

```vue
<script setup lang="ts">
import { usePlainAnalytics } from '@plainapps/analytics-vue';

const { setEnabled, isEnabled } = usePlainAnalytics();

function handleConsentChange(consent: boolean) {
  setEnabled(consent);
}
</script>

<template>
  <div>
    <label>
      <input type="checkbox" :checked="isEnabled" @change="handleConsentChange($event.target.checked)" />
      Allow analytics
    </label>
  </div>
</template>
```

### Global Properties Access

The plugin also exposes analytics via `$analytics` on the app instance:

```vue
<script>
export default {
  methods: {
    trackWithOptions() {
      this.$analytics.trackEvent('legacy_event', { source: 'options-api' });
    }
  }
}
</script>
```

## Vite Configuration

No special configuration needed. Just install and use:

```ts
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
});
```

## TypeScript

Full TypeScript support is included. Import types as needed:

```ts
import type {
  PlainAnalyticsContext,
  PlainAnalyticsPluginOptions,
  EventProperties,
  Goal,
} from '@plainapps/analytics-vue';
```

## License

MIT