vue.jsnuxt.jsmixpanel

How to use Mixpanel in Nuxt.js


How one can include Mixpanel analytics in Nuxt.js?

Honestly, I'm new to Nuxt.js and Vue, and Mixpanel but website I inherited is descant so I'd rather learn than change. Adding Google Analytic is pretty straight forward as there's a great package nuxtjs google-analytics; it only requires adding googleAnalytics to Nuxt config and all is done magically.

For Mixpanel I have found both vue-mixpanel and mixpanel-browser but I'm not really sure how to use them. The first one seems appropriate but once I initiate the plugin I'm confused where to use the this.$mixpanel references. Is there some "on page load" event? No idea how to add something to page's header.


Solution

  • With Nuxt you have layouts. Each page is going to be utilizing a layout. You can add a watcher to the $route object, and determine when it changes and track the page views in this way fairly easily.

    // layouts/default.vue (or whatever layout is being used)
    
    watch: {
      $route: {
        handler: function () {
          // from the vue-mixpanel documentation
          this.$mixpanel.track('event name', {
            distinct_id: 'unique client id',
          })
        },
        immediate: true // fires this function immediately when the object has bound to the watcher
    
      }
    }
    

    Mind you that if different pages use different layouts, they'll need to all implement this same logic, which you could abstract into a mixin.