Vue3 接入Google AdSense
1 年前

vue3

66

vue3引入谷歌广告方法
前言:个人博客 我的博客网站也是通过这样的方法接入,不添加插件

为什么选择谷歌广告

门槛低,作为新生站点,缺的是内容和流量, 国内最大就是百度联盟,但是对这2点都有要求。
相比较之下除了对内容审核是否灰色以外,对流量要求不大

vue3接入

前置条件:已经在Google AdSense 中 添加网站 && 通过审核 && 已经创建广告单元
我这里项目是quasar V2 ssr,主要以项目为主讲解
index.template.html 对标 正常vue项目 index.html

//index.template.html
/* *
在head标签中添加 script
【 **** 】:你的发布商 ID
*/
<script async 
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=****"
crossorigin="anonymous"
>
</script>
1
2
3
4
5
6
7
8
9
10
//index.template.html
//在body标签中为window添加函数
<body>
 
  <div id="q-app"></div>

  <script>
    window['addAds'] = function () {
      let chlid = document.getElementsByClassName('adsItem')
      for (let index = 0; index < chlid.length; index++) {
        (adsbygoogle = window.adsbygoogle || []).push({});
      }
    }
  </script>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

组件中应用

onMounted(() => {
  window.addAds();
});
1
2
3
//将广告单元代码添加到盒子中
<template>
  <div class="col adsItem">
      <ins
        class="adsbygoogle"
        style="display: block"
        data-ad-client="**"
        data-ad-slot="**"
        data-ad-format="auto"
        data-full-width-responsive="true"
       ></ins>
   </div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13

注意事项

Google AdSense 中添加域名 ,本地开发时会 广告返回403。只有运行对应谷歌添加域名,才会显示

Google AdSense 广告单元有几种,根据需要添加