How to add Google AdSense to a Vuejs app?

In the article How to add Google AdSense to your React application? we have learned about How to add Google AdSense to your React app, today we'll do the same with a Vuejs app.

The first step, add Google AdSense script to head tag (In the index.html static file):

    <script>
      async
      data-ad-client="ca-pub-yourGoogleAdId"
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
    </script>


Second: Create Google Adsense Component to re-use in wherever you want:




With scripts below:

export default {
  name: "GoogleAd",
  props: {
    timeout: Number,
    classNames: String,
    slot: String
  },
  data() {
    return {
      googleInit: null,
      googleAdId: "ca-pub-yourGoogleAdId"
    };
  },
  mounted() {
  	let timeout = 200;
    if(this.timeout) timeout = this.timeout;
    this.googleInit = setTimeout(() => {
      if (typeof window !== "undefined")
        (window.adsbygoogle = window.adsbygoogle || []).push({});
    }, timeout);
  },
  destroyed() {
    if (this.googleInit) clearTimeout(this.googleInit);
  }
};


Props:

- classNames: String => To add custom class name to style your Google Ads
- slot: String => To insert data-ad-slot that you get from Google AdSense
- timeout: Number (default is 200 milliseconds) => To time delay for your Ads after the page rendered (optional)

Note: replace ca-pub-yourGoogleAdId with your Google Ad Id


Finally, add your GoogleAd component into your site, where you'd like to display, example:




Script:

import GoogleAdSense from "./components/GoogleAdSense";

export default {
  name: "App",
  components: {
    GoogleAdSense
  }
};


That's it!

© 2019 4codev

Created with love by Sil.