Skip to content

Commit 190dee5

Browse files
committed
composition api
1 parent f0b9b9c commit 190dee5

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

contents/docs/libraries/vue-js.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,77 @@ export default {
210210
}
211211
```
212212

213+
### Method 4: Use the Composition API
214+
215+
Create a new folder `composables` in your project. In that folder, create a new file `usePosthog.js` with the following initialization code:
216+
217+
```js
218+
// composables/usePostHog.js
219+
import { provide, inject } from 'vue'
220+
import posthog from 'posthog-js'
221+
222+
const PostHogSymbol = Symbol('PostHog')
223+
224+
export function usePostHogProvider() {
225+
const posthogInstance = posthog.init(
226+
"<ph_project_api_key>",
227+
{
228+
api_host: "<ph_client_api_host>",
229+
person_profiles: 'identified_only'
230+
}
231+
)
232+
233+
provide(PostHogSymbol, posthogInstance)
234+
235+
return posthogInstance
236+
}
237+
238+
export function usePostHog() {
239+
const posthogInstance = inject(PostHogSymbol)
240+
if (!posthogInstance) {
241+
throw new Error('PostHog has not been provided')
242+
}
243+
return posthogInstance
244+
}
245+
```
246+
247+
In `App.vue`, call `usePostHogProvider()` to initialize PostHog.
248+
249+
```js
250+
// ...rest of your app
251+
</template>
252+
253+
<script setup>
254+
import { usePostHogProvider } from './composables/usePostHog'
255+
256+
// Initialize and provide PostHog
257+
usePostHogProvider()
258+
</script>
259+
260+
<script>
261+
// ...rest of your app
262+
```
263+
264+
You can then use `usePostHog()` to access PostHog in any component.
265+
266+
```js
267+
<template>
268+
<div>
269+
<button @click="trackEvent">Track Event</button>
270+
</div>
271+
</template>
272+
273+
<script setup>
274+
import { usePostHog } from '../composables/usePostHog'
275+
276+
const posthog = usePostHog()
277+
278+
const trackEvent = () => {
279+
posthog.capture('button_clicked', { property: 'value' })
280+
}
281+
</script>
282+
```
283+
213284
## Capturing pageviews
214285

215286
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.

0 commit comments

Comments
 (0)