Skip to content

Commit 0e59f8a

Browse files
authored
Simplify API to access utm parameters (#27)
* feat(composables): create useNuxtUTM composable * feat(module): add import for useNuxtUTM composable * refactor(playground): use composable * chore: update Readme
1 parent eac2409 commit 0e59f8a

File tree

4 files changed

+26
-5
lines changed

4 files changed

+26
-5
lines changed

README.md

+12-1
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,25 @@ That's it! You can now use Nuxt UTM in your Nuxt app ✨
5353

5454
## Usage
5555

56+
You can use ```useNuxtUTM``` composable to access the UTM object:
57+
58+
```vue
59+
<script setup>
60+
const utm = useNuxtUTM();
61+
</script>
62+
```
63+
> Remember: You don't need to import the composable because nuxt imports it automatically.
64+
65+
Alternatively, you can get the UTM information through the Nuxt App with the following instructions:
66+
5667
```vue
5768
<script setup>
5869
import { useNuxtApp } from "nuxt/app";
5970
const { $utm } = useNuxtApp();
6071
</script>
6172
```
6273

63-
The `$utm` will contain an array of UTM parameters collected for use. Each element in the array represents a set of UTM parameters collected from a URL visit, and is structured as follows:
74+
Regardless of the option you choose to use the module, the `utm' object will contain an array of UTM parameters collected for use. Each element in the array represents a set of UTM parameters collected from a URL visit, and is structured as follows
6475

6576
```js
6677
[

playground/app.vue

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
<template>
22
<div>Nuxt 3 UTM module playground!</div>
3-
<pre>{{ $utm }}</pre>
3+
<pre>{{ utm }}</pre>
44
</template>
55

66
<script setup>
7-
import { useNuxtApp } from "nuxt/app";
7+
import { useNuxtUTM } from '#imports';
88
9-
const { $utm } = useNuxtApp();
9+
const utm = useNuxtUTM();
1010
</script>

src/module.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { defineNuxtModule, addPlugin, createResolver } from "@nuxt/kit";
1+
import { defineNuxtModule, addPlugin, addImports, createResolver } from "@nuxt/kit";
22

33
// Module options TypeScript interface definition
44
export interface ModuleOptions {}
@@ -15,5 +15,9 @@ export default defineNuxtModule<ModuleOptions>({
1515

1616
// Do not add the extension since the `.ts` will be transpiled to `.mjs` after `npm run prepack`
1717
addPlugin(resolver.resolve("./runtime/plugin"));
18+
addImports({
19+
name: 'useNuxtUTM',
20+
from: resolver.resolve('runtime/composables'),
21+
})
1822
},
1923
});

src/runtime/composables.ts

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { useNuxtApp } from '#imports'
2+
3+
export const useNuxtUTM = () => {
4+
const nuxtApp = useNuxtApp()
5+
return nuxtApp.$utm
6+
}

0 commit comments

Comments
 (0)