首页 > 解决方案 > 尝试在 vuejs 中重新渲染广告

问题描述

嘿,我是新来的,所以如果我做了一些愚蠢的事情,请不要怪我:D 所以是的,我的问题!我有一个带有 vuejs 的网站,我想在我的网站上放一些广告。所以我创建了一些组件:

<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>

很好,但如果我尝试转到我网站上的另一个页面,广告不会刷新和消失。
我试图清除标签

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

但不起作用有没有人有想法?

标签: javascriptvue.js

解决方案


好的,我想通了,所以谷歌没有清除内部 HTML,而是提供了一个刷新属性,所以我只是替换了

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

和:

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

推荐阅读