gtm-module
gtm-module copied to clipboard
Typescript
Hi all,
In my nuxt TS project i cant access the $gtm variable. Do i need to declare it in index.d.ts? If so, can anybody give me an hint to make it happen in TS?
Thank you
Hey ! That's how we fixed it : nuxt.d.ts
declare module "vue/types/vue" {
interface Vue {
$gtm: {
pushEvent(event: { event: DatalayerEvents; [key: string]: any }): void;
};
}
}
Yoo!!
Thank you it worked!
Hello @MFrizzy . I have the same problem but when I use your code I receive the following error: "Cannot find name 'DatalayerEvents'"
Hey @igor-pereira
That's a custom type i've made with my GTM Events :
type DatalayerEvents = "login" | "register";
You can use an enumeration if you want ;)
Hey @MFrizzy I managed to make it work using:
declare module "vue/types/vue" { interface Vue { $gtm: { push(event: { event: string; [key: string]: any }): void; }; } }
Doing this hack works for $gtm, but then other types don't work anymore.
this.$store this.$root this.$i18n ...
Hey @MFrizzy I managed to make it work using:
declare module "vue/types/vue" { interface Vue { $gtm: { push(event: { event: string; [key: string]: any }): void; }; } }
Doing this hack works for $gtm, but then other types don't work anymore.
this.$store this.$root this.$i18n ...
Hey @MFrizzy I managed to make it work using: declare module "vue/types/vue" { interface Vue { $gtm: { push(event: { event: string; [key: string]: any }): void; }; } }
Had the same problem, make sure to import vue in the .d.ts file first, otherwise you're overriding the Vue interface instead of augmenting it.
Like this:
import 'vue'
declare module 'vue/types/vue' {
interface Vue {
$gtm: {
push(event: { event: string; [key: string]: any }): void;
};
}
}
I was facing the same issue, I needed to use $gtm on custom plugins so I also added the typing there. Notice that I am using event?
because sometimes I don't need to pass it but I disagree with this approach so if you always pass event you can take out the ?
.
I followed Nuxt TypeScript Docs.
import 'vue'
declare module "vue/types/vue" {
// this.$gtm inside Vue components
interface Vue {
$gtm: {
push(event: {event?: string, [p: string]: any}): void
};
}
}
declare module '@nuxt/types' {
// nuxtContext.app.$gtm inside asyncData, fetch, plugins, middleware, nuxtServerInit
interface Context {
$gtm: {
push(event: {event?: string, [p: string]: any}): void
};
}
}
declare module 'vuex/types/index' {
// this.$gtm inside Vuex stores
// eslint-disable-next-line @typescript-eslint/no-unused-vars,unused-imports/no-unused-vars
interface Store<S> {
$gtm: {
push(event: {event?: string, [p: string]: any}): void
};
}
}```