3 Steps to Add AdSense to a Vue.js App

Modern JavaScript frameworks like Vue.js have exploded in popularity in recent years. Still, there are some tasks which don’t have an obvious solution. For example, adding Adsense typically involves adding a script and a predefined HTML element provided by Google. This process doesn’t match how you typically add functionality to a Vue app. Luckily, there is a package that does a great job of simplifying the process of using Adsense with Vue.

This article assumes you’ve already been approved for AdSense and have created at least one ad unit in AdSense.

Step 1. Install vue-google-adsense

First, install the vue-google-adsense package to your project as well as vue-script2 (this is used to add AdSense <script> tags to the page):

npm install vue-script2 vue-google-adsense --save

Step 2. Register Component

Next, you need to register the Adsense component with Vue. Since you’ll likely be using it in multiple components, you’re probably best off registering the component in your main.js as follows:

import Ads from 'vue-google-adsense'
Vue.use(require('vue-script2'))
Vue.use(Ads.Adsense)

Step 3. Add to Vue.js Template

With the component registered, you’re ready to start adding it to your app. Simply copy and paste the attribute values from the HTML provided by Google into the matching component props.

Below is an example using psuedo publisher and slot IDs:

<template>
  <div class="ad-container">
    <Adsense
      data-ad-client="ca-pub-1234567891234567"
      data-ad-slot="1234567890"
      data-ad-format="auto"
      :data-full-width-responsive="true"
    >
    </Adsense>
  </div>
</template>

As shown in the template above, I always wrap my ad units in an “ad-container” div so I can style it as necessary. Mainly because Adsense ad units are terrible about taking up more of the page than you expect.

Done!

And there you have it, Adsense in a Vue app made easy.

The above example uses the basic Adsense component which represents the Display ad unit type in Adsense. In-article and In-feed ad unit types are also supported:

Vue.use(Ads.InArticleAdsense)
Vue.use(Ads.InFeedAdsense)

Check out the package’s github page of you want to learn more about all the settings it exposes.