Kiran Muralee
Kiran Muralee

Reputation: 2060

Integrate Google Optimize in Nuxt application

I am trying to use Google Optimize in my Nuxt application. I need a way to fire an activation event after any of the page components gets updated. The problem currently is there can be data that is being returned by API and using the API data the DOM gets re-rendered in page load. I need to fire the activation event after that. The google docs for firing activation events in SPA is given below Firing activation in a single page application

For the angular app, it is accomplished by adding

myapp.run(function($rootScope, $timeout) {
   $rootScope.$watch(function(){
     $timeout(function(){
       dataLayer.push({'event': 'optimize.activate'});
     },0,false);
   })
})

I am looking for a similar kind of alternative in my Nuxt application

I know that inside a component, I can listen for the updated life cycle hook after content has been updated and DOM has been re-rendered. But I need a way to execute some code in a central place when any of the components got updated or DOM gets re-rendered.

What I have used is I created a global mixin (globalMixin.js) inside the plugins directory and used it's updated lifecycle method. So this mixin code gets injected into every component and the update method gets called if any of those component data gets changed. But I am doubting this approach as an ideal solution.

Can anyone suggest to me a better approach to doing this task or does Nuxt/Vue has any standard way of doing this? The code inside plugins/globalMixin.js is given below:

if (!Vue.__my_mixin__) {
      Vue.__my_mixin__ = true
      Vue.mixin({
        updated() {
        ..execute some code
       }
     }) 
    } 

Upvotes: 5

Views: 1203

Answers (1)

Brewal
Brewal

Reputation: 8189

You should use a store such as Vuex to handle the local state of your application.

You can then retrieve the state of the store in any page or component. I recommend using vuex-map-fields

Upvotes: 1

Related Questions