t1ggy
t1ggy

Reputation: 21

Try rerender ads in vuejs

Hey i'm new here so please dont blame me if i do something stupid :D So yeah my question! I have a site with vuejs and i want to put some ads on my site. So i created some components:

<template>
  <div class="ad-wrapper">
    <div ref="ad"></div>
    <div id='div-gpt-ad-1407836229438-0' ref="adGpt"></div>
  </div>
</template>

<script>
export default {
  name: 'Ad-top',
  props: {
  },
  components: {
  },
  data() {
    return {
    };
  },
  methods: {
    setAd() {
      const adScript = document.createElement('script');
      adScript.type = 'text/javascript';
      adScript.text = `googletag.cmd.push(function() {
        googletag.defineSlot('/53015287/aniflix.tv_d_970x90_1', [970, 90], 'div-gpt-ad-1407836229438-0').addService(googletag.pubads());

        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
      });`;
      this.$refs.ad.appendChild(adScript);

      const adGptScript = document.createElement('script');
      adGptScript.type = 'text/javascript';
      adGptScript.text = `googletag.cmd.push(function() { googletag.display('div-gpt-ad-1407836229438-0'); });`;
      this.$refs.adGpt.appendChild(adGptScript);
    },
    refreshAd() {
      this.$refs.ad.innerHTML = '';
      this.$refs.adGpt.innerHTML = '';
      this.setAd();
    },
  },
  mounted() {
    this.setAd();

    this.$eventBus.$on('refreshAds', () => {
      this.refreshAd();
    });
  },
  beforeDestroy() {
    this.$eventBus.$off('refreshAds');
  },
};
</script>

Well that works just fine but if i try to go to another page on my sites the ads doesnt refresh and disappear.
I tried to just clear the tags

refreshAd() {
      this.$refs.ad.innerHTML = '';
      this.$refs.adGpt.innerHTML = '';
      this.setAd();
    },

But doesnt work Does anyone have an idea?

Upvotes: 1

Views: 303

Answers (1)

t1ggy
t1ggy

Reputation: 21

Ok i figured it out so instead of clearing the inner HTML google provides a refresh attribute so i just replaced

refreshAd() {
      this.$refs.ad.innerHTML = '';
      this.$refs.adGpt.innerHTML = '';
      this.setAd();
    },

with:

refreshAd() {
googletag.cmd.push(function() { googletag.pubads().refresh(); });
},

Upvotes: 1

Related Questions