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