v-ga

This directive allows us to centralize all track events in one object and share it across the entire application without needs to add extra logic to our component methods

Taking as an example a button that only has to log a name in the console

  1. <template>
  2. <button @click="logName">Log me</button>
  3. </template>
  4. <script>
  5. export default {
  6. name: 'myComponent',
  7. data () {
  8. return {
  9. name: 'John'
  10. }
  11. },
  12. methods: {
  13. logName () {
  14. console.log(this.name)
  15. }
  16. }
  17. }
  18. </script>

To start tracking the value of name we can start by adding a method in the commands object that handles this action

  1. import Vue from 'vue'
  2. import VueAnalytics from 'vue-analytics'
  3. Vue.use(VueAnalytics, {
  4. id: 'UA-XXX-X',
  5. commands: {
  6. trackName (name = 'unknown') {
  7. this.$ga.event('randomClicks', 'click', 'name', name)
  8. }
  9. }
  10. })

Lets take in mind that every function we write in the commands object is also bound to the current component scope, so that we have access to the Vue instance prototype object and eventually to methods, data and computed values of the component itself. (I do not recommend to use any component specific properties to avoid the method to be coupled to a specific component structure)

Then we only need to add the v-ga directive to your element and access the method from the commands list that now is shared in the $ga object

  1. <template>
  2. <button
  3. v-ga="$ga.commands.trackName.bind(this, name)"
  4. @click="logName">
  5. Log me
  6. </button>
  7. </template>
  8. <script>
  9. export default {
  10. name: 'myComponent',
  11. data () {
  12. return {
  13. name: 'John'
  14. }
  15. },
  16. methods: {
  17. logName () {
  18. console.log(this.name)
  19. }
  20. }
  21. }
  22. </script>

By default, the directive is executed when the element is clicked. However, if you want to change the event type for the logging, you can add the proper event as a modifier.

  1. <template>
  2. <input
  3. v-model="name"
  4. v-ga.focus="$ga.commands.trackFocus.bind(this, 'name')" />
  5. </template>
  6. <script>
  7. export default {
  8. name: 'myComponent',
  9. data () {
  10. return {
  11. name: 'John'
  12. }
  13. },
  14. methods: {
  15. logName () {
  16. console.log(this.name)
  17. }
  18. }
  19. }
  20. </script>

If there’s no need to pass any arguments, we could also just pass the name of the method as a string, and the plugin will look it up for us

  1. <template>
  2. <button v-ga="'trackName'">Click me</button>
  3. </template>
  4. <script>
  5. export default {
  6. name: 'myComponent'
  7. }
  8. </script>