第一步,将 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 }};