如何将 Google AdSense 添加到 Nuxt.js ?

第一步,将 Google AdSense 脚本添加到 head 标籤(app.html 文件内):

<script  async   src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxx"  crossorigin="anonymous"></script>

第二:创建 Google Adsense 组件以在您想要的任何地方重複使用:

<div :class="classNames">    <ins      :className="adsbygoogle"      :style="{display: 'block'}"      :data-ad-client="googleAdId"      :data-ad-slot="slot"      data-ad-format="auto"      data-full-width-responsive="true"    ></ins>  </div>

并使用下列script:

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 => 添加自订义的class风格给 Google Adsslot: String => 插入 Google AdSense 给的slot值timeout: Number (默认200ms) => 页面呈现后,广告的延迟时间(可有可无)

Note: 将ca-pub-yourGoogleAdId替换为自己的 Google Ad Id

最后,将您的 GoogleAd 组件添加到想要显示的页面中,ex:

<template>  <GoogleAdSense slot="123456789" :timeout="200" classNames="mx-auto"/></template>

Script:

import GoogleAdSense from "~/components/GoogleAdSense";export default {  name: "App",  components: {    GoogleAdSense  }};

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章