Skip to content

Commit

Permalink
composition api
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanagas committed Sep 19, 2024
1 parent f0b9b9c commit 190dee5
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions contents/docs/libraries/vue-js.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,77 @@ export default {
}
```

### Method 4: Use the Composition API

Create a new folder `composables` in your project. In that folder, create a new file `usePosthog.js` with the following initialization code:

```js
// composables/usePostHog.js
import { provide, inject } from 'vue'
import posthog from 'posthog-js'

const PostHogSymbol = Symbol('PostHog')

export function usePostHogProvider() {
const posthogInstance = posthog.init(
"<ph_project_api_key>",
{
api_host: "<ph_client_api_host>",
person_profiles: 'identified_only'
}
)

provide(PostHogSymbol, posthogInstance)

return posthogInstance
}

export function usePostHog() {
const posthogInstance = inject(PostHogSymbol)
if (!posthogInstance) {
throw new Error('PostHog has not been provided')
}
return posthogInstance
}
```

In `App.vue`, call `usePostHogProvider()` to initialize PostHog.

```js
// ...rest of your app
</template>

<script setup>
import { usePostHogProvider } from './composables/usePostHog'

// Initialize and provide PostHog
usePostHogProvider()
</script>

<script>
// ...rest of your app
```

You can then use `usePostHog()` to access PostHog in any component.

```js
<template>
<div>
<button @click="trackEvent">Track Event</button>
</div>
</template>

<script setup>
import { usePostHog } from '../composables/usePostHog'

const posthog = usePostHog()

const trackEvent = () => {
posthog.capture('button_clicked', { property: 'value' })
}
</script>
```

## Capturing pageviews

You might notice that moving between pages only captures a single pageview event. This is because PostHog only captures pageview events when a [page load](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event) is fired. Since Vue creates a single-page app, this only happens once, and the Vue router handles subsequent page changes.
Expand Down

0 comments on commit 190dee5

Please sign in to comment.