Last active
December 12, 2024 08:29
-
-
Save matt-e-king/ebdb39088c50b96bbbbe77c5bc8abb2b to your computer and use it in GitHub Desktop.
Vuex plugin for VueGtm (Google Tag Manager) (https://github.com/mib200/vue-gtm)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Using the Vuex plugin pattern: https://vuex.vuejs.org/en/plugins.html, | |
this plugin will fire off a gtm.trackEvent for each mutation that occurs within your app. | |
It will also do a lookup on a literal object methods named after your mutation types. From those methods, | |
return a object with looks up on the store. | |
*/ | |
import Vue from 'vue' | |
// import mutation-types, see example: | |
/** | |
import { | |
USER_LOGIN, | |
USER_LOGOUT | |
} from '../mutation-types' | |
*/ | |
const mutationLookup = { | |
// put methods here named after mutation names | |
// see example below | |
} | |
/** | |
const mutationLookup = { | |
USER_LOGIN(store) { | |
return { email: store.user.email } | |
}, | |
USER_LOGOUT(store) { | |
return { email: store.user.email } | |
} | |
} | |
*/ | |
export default function gtmPlugin(store) { | |
store.subscribe((m, s) => { | |
try { | |
let mutation = m.type.split('/')[0] | |
let payload = mutationLookup[mutation] && mutationLookup[mutation](s) | |
if (payload) { | |
Vue.gtm.trackEvent({ | |
event: 'mutation', | |
noninteraction: mutation, | |
...payload | |
}) | |
} | |
} catch(e) { | |
throw new Error(`Error with gtm.trackEvent: ${e}`) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment